Solve the cross domain problem of downloading files on the service with the download attribute of the a tag of H5

Keywords: Javascript Attribute html5

1. Download multimedia files (pictures / videos / files, etc.) by clicking

  • The easiest way:

    <a href='url' download="filename.ext">Download File</a>
  • If the url points to the same source, it is normal.
  • If the url points to a third-party resource, the download will fail, and the performance is the same as when the download is not used -- the files that can be opened by the browser will be opened directly by the browser, and the files that cannot be opened will be downloaded directly. The file opened by browser can be downloaded manually.

    • Solution 1: package the file as a file that cannot be opened by browsers such as. zip/.rar to download.
    • Solution 2: forward through the back-end, the back-end requests the third-party resources and returns them to the front-end. The front-end uses file saver and other tools to save files.

 

  • If the url points to a third-party resource with CORS configured, the download attribute is invalid, but the file can be obtained and downloaded locally, and the file name cannot be modified.

2. Solutions

1. Download text information file with HTML5 Blob

const downloadRes = async (url, name) => {
    let response = await fetch(url)
    // Content to blob address
    let blob = await response.blob()
    // Create hidden downloadable links
    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 this picture into base64 Format, and then download.
```
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;
};
```


Posted by bobthebuilder on Fri, 25 Oct 2019 14:15:19 -0700