简体   繁体   中英

I have a problem downloading xlsx file from API rest on JS

Im working on ReactJs. I have a button that downloads a excel file that is provided from an API REST.The problem is that i read all the content from the response and then i download all this information on a string.

But i have been trying all different stuff and i allways have the same problem, when i try to open the file in Excel,it show a message saying that the file is corrupted. This is my code:

export const getFilesFromApi = (path, callBack, contentType) => apiFileCalls({ path, method: 'GET', callBack, contentType: contentType || 'text/plain' });

export const apiFileCalls = ({ path, callBack, data, method, contentType, attachFiles = [], additionalHeaders = [] }) => {
    debugger;
    new Promise(() => {
        const request = superagent(method, path);
        request.set('Access-Control-Allow-Origin', '*');
        if (contentType) {
            request.set('Content-Type', contentType);
        }
        const accessToken = getCookie_accessToken();
        if (accessToken) {
            request.set('Authorization', `Bearer ${accessToken}`);
        }
        if (data) {
            request.send(data);
        }

        additionalHeaders.forEach((header) => request.set(header.name, header.value));
        attachFiles.forEach((file) => request.attach(file.fieldName, file.file));

        request.query().then((res) => callBack(res.text)).catch((error) => {
            if (error.status !== 401) {
                callBack(true, error.response);
            }
        });
    });
};
export const downloadFile = (content, fileName) => {
    debugger;
    const urlrtMP = window.URL.createObjectURL(new Blob([ content ]));
    const link = document.createElement('a');
    link.href = urlrtMP;
    link.setAttribute('download', fileName);
    link.click();
};

Any help? Thanks a lot

You have to use responseType('blob') for receiving Blob content.

Ref: https://visionmedia.github.io/superagent/#binary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM