首页 > 解决方案 > 通过 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)
    }
  }
}

标签: node.jsreactjsexpressdownloadupload

解决方案


我猜您正在下载一个 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
      }
}

另外,您应该设置responseTypearraybuffer,


推荐阅读