[英]I have a problem downloading xlsx file from API rest on JS
我正在研究 ReactJs。 我有一個按鈕可以下載一個從 API REST 提供的 excel 文件。問題是我從響應中讀取了所有內容,然后我將所有這些信息下載到一個字符串中。
但是我一直在嘗試所有不同的東西,我總是遇到同樣的問題,當我嘗試在 Excel 中打開文件時,它顯示一條消息說文件已損壞。 這是我的代碼:
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();
};
有什么幫助嗎? 非常感謝
您必須使用 responseType('blob') 來接收 Blob 內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.