【发布时间】:2020-11-10 03:00:09
【问题描述】:
在客户端,它是一个反应应用程序。我设置了一个端点,我可以从中请求文件。然而,从 pdfs、pngs 到 excel 文件的每个文件在尝试从服务器下载时似乎都已损坏,无法成功打开这些文件中的任何一个。想知道是否有人对此有任何见解。一直找不到任何有效的方法。
后端和前端的代码见下文。
后端node.js
ChangeLogAttachment_read(req, res, id, file_path, file_type)
.then(resp => {
res.download(file_path, file_name, (error)=>{
if(error) {
console.log("Error", error);
}
});
// Tried these
// res.contentType(file_type);
// res.send(fs.readFileSync(file_path));
// res.send(resp)
})
.catch(err => {
err.location = 'Error in NS_Controller.changeLogAttachments read.';
log.error(err)
});
前端 - 反应
requestFile = (id, filePath, fileName , fileType)=> {
let token = AuthUtils.getToken();
let data = {};
data['action'] = 'read';
data['id'] = id;
data['file_path'] = filePath;
data['file_type'] = fileType;
data['file_name'] = fileName;
axios({
url: process.env.REACT_APP_HOST +
process.env.REACT_APP_PORT + '/pbx/changelog/attachments',
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
responseType:'blob'
},
timeout: 10000,
data
}).then(response=> {
console.log("Response", response);
const url = window.URL.createObjectURL(new Blob([response.data]));
// const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName); //or any other extension
document.body.appendChild(link);
link.click();
}).catch(error=> {
console.log("Error", error);
})
}
【问题讨论】: