node.js - 通过 expressjs 下载的文件全部损坏
问题描述
当我尝试使用 expressjs 的 res.download() 从我的 Nodejs 服务器下载文件时,我尝试的所有文件类型都会导致文件损坏。我下载的文件都和上传的一样大,例如 PDF 的页数完全相同,只是空的。上传文件似乎工作正常。
我可能忽略了一些东西,但我不知道是什么。
反应'getFile'
const getFile = () => {
API.instance.get(`${downloadUrl}/download/${file.name}`)
.then((result) => {
fileDownload(result.data, file.name)
}
}
Nodejs'下载文件'
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);
}
反应'上传文件
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
,
推荐阅读
- ios - 当我单击我使用 Swift 和 xcode 构建的应用程序中的按钮时,它们不起作用
- python - 使用 print r"\" (Python) 仅打印一个斜杠
- go - golang 编译器何时可以重新排序命令以及同步原语如何影响它?
- apache-spark - 在 spark-shell 中运行带有换行符的 scala 脚本
- java - Java equals() 看似返回错误的布尔值
- tsql - 我想一次获取数据库中所有表的计数(*)以及 DataBricks SQL 中的“Table_Name”
- java - 如何在 IntelliJ IDEA 中的变量下方自动生成 Getter()?
- c - wzip.c OS 三个简单的步骤
- php - 如何使用手机强制在 php 服务器中下载文件?
- ios - 如何附加到另一个视图控制器上的数组