Native to achieve js file to download several cases

Content Source:

https://www.cnblogs.com/ajaxkong/p/11686041.html

1: typically by way of a tag download using Download property of H5

Code examples are as follows:

Scene: suitable for a modern browser, url is the download address, rather than the file stream, commonly used in the GET request

Copy the code
 1 function downLoad(downUrl, fileName) {
 2 let a = document.createElement ( "a"); // create a label
 3   if ('download' in a) {
 4 a.download = fileName; // set the download file name
 5   }
 6   (document.body || document.documentElement).appendChild(a);
 7 a.href = downUrl; // downUrl for the return of the background Download
 8   a.target = '_parent';
 9 a.click (); // Set the click event
10 a.remove (); // remove a label
11 }
12 
13 downLoad (URL, 'test.xlxs') // URL Download
Copy the code

 

If the background to a file stream, then packaging it in favor Blob object file stream, commonly used in the POST request

Code examples are as follows:

Copy the code
 1 function downLoad(content, fileName) {
 2 let a = document.createElement ( "a"), // create a label
 3 blob = new Blob ([content]); // with the object-packaged Blob file stream
 4 
 5   if ('download' in a) {
 6 a.download = fileName; // set the download file name
 7   }
 8   (document.body || document.documentElement).appendChild(a);
 9 a.href = window.URL.createObjectUrl (blob) ;; // file content to the stream returned backstage
10 a.click (); // Set the click event
11 a.remove (); // remove a label
12 }
13 downLoad ( 'I'm a file stream file stream I', 'test.txt')
Copy the code

If the POST request, can be implemented by means of axios, with FileReader object.

Copy the code
 1 axios.post(downloadUrl, this.searchParams, {
 2   responseType: 'blob'
 3 }).then(res => {
 4   const blob = res.data
 5   const reader = new FileReader()
 6   reader.readAsDataURL(blob)
 7   reader.onload = (e) => {
 8     const a = document.createElement('a')
 9 a.download = `table name .xlsx`
10     a.href = e.target.result
11     document.body.appendChild(a)
12     a.click()
13     document.body.removeChild(a)
14   }
15 }).catch(err => {
16   console.log(err.message)
17 })
Copy the code

2: With Base64 implementation file download

For non-text files, but also can make use of JS download, such as downloading pictures, the front end can be directly converted into base64 and download

Bar code directly on an instance, should all be able to understand, I do not say,

Code from Zhangxin Xu Bowen about downloading, you can directly view

Copy the code
 1 function download (domImg, filename) {
 2 // create hidden download link
 3   let eleLink = document.createElement('a');
 4   eleLink.download = filename;
 5   eleLink.style.display = 'none';
 6 // pictures turn base64 address
 7   let canvas = document.createElement('canvas');
 8   let context = canvas.getContext('2d');
 9   let width = domImg.naturalWidth;
10   let height = domImg.naturalHeight;
11   context.drawImage(domImg, 0, 0);
12 // If PNG picture, canvas.toDataURL ( 'image / png')
13   eleLink.href = canvas.toDataURL('image/jpeg');
14 // trigger click
15   document.body.appendChild(eleLink);
16   eleLink.click();
17 // then removed
18   document.body.removeChild(eleLink);
19 };
Copy the code

 3: By way formData label download, which is safe and easy way to download the products used to build, compatible with low version of the browser

Directly on the code, because it involves the endorsement of practical experience and peace sign business, so I can not read do not read, directly on the code for their own future reference

Copy the code
 1 function downfile(file) {
 2   if (file == undefined || file == null) {
 3     return;
 4   }
 5   const nonce = Math.floor(Math.random() * (Math.floor(100) - Math.ceil(1))) + Math.ceil(1);
 6   const timestamp = parseInt(Date.now() / 1000);
 7   const searchParams = {
 8 storageKey: file.storageKey, // file system key
 9 tokenType: 2, // token type of application, 1: Upload, 2: Download, 5: Preview
10     nonce,
11     timestamp,
12 gen "MD5"
13   };
14   axios({ url: '/docs/api/file/token/applyToken', method: 'get', params: searchParams })
15     .then(res => {
16       if (!res.status === 200 || !res.data) {
17         return;
18       } if (!res.data.success) {
? 19 const msg = res.data.msg && res.data.msg.length> 0 res.data.msg: 'download failed! ';
20         message.error(msg);
21 
22       } else {
23         res = res.data || {};
24         let content = {};
25         if (res.data.contentList && res.data.contentList.length > 0) {
26           content = res.data.contentList[0];
27         }
28         return {
29           nodeUrl: content.nodeUrl,
30           token: content.token
31         }
32       }
33     }).then(({ nodeUrl, token }) => {
34 const url = `$ {nodeUrl} / node / download / view / $ {file.storageKey}`; // file download path
35       const form = document.createElement('form');
36       form.setAttribute("method", "get");
37       form.setAttribute("name", "theForm");
38       form.setAttribute("target", "_self");
39       form.setAttribute('style', 'display:none');
40       form.setAttribute("action", url);
41       document.body.appendChild(form);
42 
43       const newinput_fileToken = document.createElement('input');
44       newinput_fileToken.setAttribute('type', 'hidden');
45       newinput_fileToken.setAttribute('name', 'fileToken');
46       newinput_fileToken.setAttribute('value', token)
47 
48       const newinput_fileName = document.createElement('input');
49       newinput_fileName.setAttribute('type', 'hidden');
50       newinput_fileName.setAttribute('name', 'fileName');
51       newinput_fileName.setAttribute('value', file.name)
52 
53       form.appendChild(newinput_fileToken);
54       form.appendChild(newinput_fileName);
55 
56       form.submit();
57       document.theForm.parentNode.removeChild(form);
58     });
59 }

Guess you like

Origin www.cnblogs.com/zwjun/p/12623294.html