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

files downloaded via expressjs are all corrupted

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

我可能忽略了一些东西,但我不知道是什么。

反应 'getFile'

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

Node.js '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
    })
}

Node.js 'uploadFile'

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