通过expressjs下载的文件都已损坏



当我尝试使用expressjs的res.download((从Nodejs服务器下载文件时,我尝试的所有文件类型都会导致文件损坏。我下载的文件都和上传的一样大,例如PDF的页面数量完全相同,只是空的。上传文件似乎工作正常。

我可能忽略了什么,但我不知道是什么。

React"getFile">

const getFile = () => {
API.instance.get(`${downloadUrl}/download/${file.name}`)
.then((result) => {
fileDownload(result.data, file.name)
}
}

Nodejs‘downloadFile’

exports.downloadFile = async (req, res) => {
const file = `./files/organisations/${req.params.organisationId}/${req.params.filename}`
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
res.download(file);
}

React上传文件

const uploadFile = e => {
e.preventDefault();
const formdata = new FormData();
formdata.append('file', selectedFile)
API.instance.post(`/organisations/${organisationId}/upload`, formdata, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(result => {
// Do stuff
})
}

Nodejs‘上传文件’

exports.uploadFile = async (req, res) => {
let file = null
if (req.files) {
file = req.files.file
// ...
// Create folder
// ...
await file.mv(`./files/organisations/${req.params.organisationId}/${file.name}`)
try {
await OrganisationModel.addFile(req.params.organisationId, file.name, req.body.userId)
res.status(200).send(req.params.organisationId)
} catch(err) {
res.status(500).send(err)
}
}
}

我猜您正在下载一个blob文件,需要使用以下代码将其转换为真实文件:

const getFile = () => {
API.instance.get(`${downloadUrl}/download/${file.name}`)
.then((result) => {
let blob = new Blob([result.data] , {type: 'application/pdf', })
var fileUrl = (window.URL || window.webkitURL).createObjectURL(blob);
newWindow.location = fileUrl
}
}

此外,您应该将responseType设置为arraybuffer

最新更新