After downloading the file from the file stream, you will be prompted that opening this type of file is not supported or the file is damaged

Download is used in react project. The back-end interface is requested to return the file stream, and the front-end processes the file stream to generate files for download.

To set responseType!!

The method adopted is the Blob method that can be found at random on Baidu. The file format to be downloaded at the beginning is pdf, but the downloaded files can't be opened with office and WPS. Let's talk about how to solve this problem. I saw someone in Baidu say that it's OK to set the responseType, but I don't believe in evil, so I don't set it. The result is really because of the responseType. After setting, the downloaded files can be opened!

Solution:
1. First, let the back-end turn the file passed down into a blank document. First of all, you can be sure that there is no problem downloading the file. In addition, the blank file can be opened with Office, and the file flow should be no problem
2. Try using the tool to simulate the request. The downloaded files can also be opened normally. Then the file flow must be OK. The problem should be at the front end
3. The backend provides methods for downloading other items, using the layUI framework. The code is as follows

//File download
function downLoadFile(ids, name) {
    //Create download request
    var oReq = new XMLHttpRequest();
    //The url parameter is the interface to get background data
    oReq.open("POST", 'Requested download address', true);
    oReq.responseType = "blob"; //Set responseType
    oReq.onload = function (oEvent) {
        var content = oReq.response;
        var elink = document.createElement('a');
        //Name is the file name returned from the background to the front end. The suffix must be added. If there is a suffix returned from the background, don't worry, otherwise it's hard to open the download locally.
        elink.download = name + ".xlsx";
        elink.style.display = 'none';
        var blob = new Blob([content], {type: "application/x-www-form-urlencoded"});
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
    };
    oReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//This is relatively unimportant
    //The user password must be placed in the request header open() and Set between send()
    oReq.setRequestHeader('Blade-Auth', 'set up balde-auth');
    oReq.send('You can set the required parameters');
}

The code I wrote is as follows

//After calling the interface, the method is called to transfer the file stream data and other required data parameters.
saveData(data, filename) {
    let blob = new Blob([data], { type: 'application/x-www-form-urlencoded' });
    let blobUrl = window.URL.createObjectURL(blob);
    const aElement = document.createElement('a');
    document.body.appendChild(aElement);
    aElement.style.display = 'none';
    aElement.href = blobUrl;
    aElement.download = filename;
    aElement.click();
    document.body.removeChild(aElement);
}

It seems that the code is the same, but my interface request is encapsulated by axios, and balde auth is also set in the encapsulation part. It seems that there is only one difference, that is, the responseType is not set. I even tried the interface request without encapsulation, and it is easy to use the top code directly, that is, the problem of responseType, Add responseType to the axios package.

/**
 * Set request interceptor and add token
 */
axios.interceptors.request.use(
    config => {
        if (config.method === 'post') {
            if(config.url.includes(url.common.filedownload)){
                config.responseType = 'blob'; //Request plus responseType
            }
        }
        return config
    },
    error => {
        message.error('Request error' + error);
        return Promise.reject(error);
    }
)

Just tell the front end of the request that you want a blob

Keywords: React

Added by kungfu71186 on Thu, 27 Jan 2022 17:02:50 +0200