[英]I have a problem downloading xlsx file from API rest on JS
Im working on ReactJs.我正在研究 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.我有一个按钮可以下载一个从 API REST 提供的 excel 文件。问题是我从响应中读取了所有内容,然后我将所有这些信息下载到一个字符串中。
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.但是我一直在尝试所有不同的东西,我总是遇到同样的问题,当我尝试在 Excel 中打开文件时,它显示一条消息说文件已损坏。 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.您必须使用 responseType('blob') 来接收 Blob 内容。
Ref: https://visionmedia.github.io/superagent/#binary参考: https : //visionmedia.github.io/superagent/#binary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.