IE browser reported an error Unhandled promise rejection Error: Access is denied. File streaming download

created at 11-03-2021 views: 1

problem

There are many export files and file download functions in the project. The front end adopts the file stream download method, which requests the back-end interface and returns the file stream.
At first, it was not clear that the ordinary method of dynamically creating a tag was not compatible with IE. Later, a bug appeared in the test on IE.
"Unhandled promise rejection Error: Access denied."

Seeing this problem, I copied Google directly, and the result is that the promise method may be wrong. After changing all the promise methods, it still reported an error. Later, I thought whether the way to create a tag was not compatible with IE, and I googled the file stream download The IE-compatible method is really rewarding, so I have the following solution, record it.

solution

The IE browser has the msSaveBlob method that comes with Microsoft, and the download of the a tag is not compatible with IE.

//Because this method is used in many places on the page, it is packaged as a component
//Don't forget to set the responseType='blob' of the request header, the react project has been encapsulated in the request
export const exportSaveData = (data, filename) => {
    let blob = new Blob([data], {type:'application/x-www-form-urlencoded' });
    let blobUrl = window.URL.createObjectURL(blob);
    if (window.navigator.msSaveBlob) {//If this method is judged, it is IE browser
        try {
            window.navigator.msSaveBlob(blob, filename)
        } catch (e) {
            console.log(e);
        }
    } else {
        // Google Chrome Create a tag and add download attribute to download
        const aElement = document.createElement('a'); //Create a tag dynamically
        document.body.appendChild(aElement); //Append the created a tag to the body
        aElement.style.display ='none'; //You can set the a tag to not be visible
        aElement.href = blobUrl; The href of the a tag is the processed blob
        aElement.download = filename;
        aElement.click();
        document.body.removeChild(aElement);
        window.URL.revokeObjectURL(blobUrl); //Release the blob object
    }
}

Perfectly solve the problem that IE cannot export

created at:11-03-2021
edited at: 11-03-2021: