The simplest way:
<a href='url' download=filename.ext>Download file</a>
If the URL points to the same source resource, it is normal.
If the URL points to a third-party resource, the download will fail, and the behavior will be the same as when download is not used - files that can be opened by the browser will be opened directly by the browser, and files that cannot be opened will be downloaded directly. Files opened by the browser can be downloaded manually.
Solution 1: Pack the file into a .zip/.rar file that cannot be opened by the browser and download it.
Solution 2: Through back-end forwarding, the back-end requests third-party resources and returns them to the front-end. The front-end uses tools such as file-saver to save the file.
If the third-party resource pointed to by the URL is configured with CORS, the download attribute is invalid, but the file can be obtained and downloaded locally, and the file name cannot be modified.
2.Solution 1. Use HTML5 Blob to download text information filesconst downloadRes = async (url, name) => { let response = await fetch(url) // Convert the content into a blob address let blob = await response.blob() // Create a hidden downloadable link let objectUrl = window.URL .createObjectURL(blob) let a = document.createElement('a') //Address a.href = objectUrl //Modify file name a.download = name // Trigger click document.body.appendChild(a) a.click() //Remove setTimeout(() => document.body.removeChild(a), 1000)}2. Picture format
If we want to download a picture, we can convert the picture to base64 format and then download it.
```export const downloadImg = async (url, name) => { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function() { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL('image/png'); let a = document.createElement('a'); a.href = dataURL; a.download = name; document .body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); canvas = null; }, 1000); }; img.src = url;};```
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.