微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过expressjs下载的文件全部损坏

如何解决通过expressjs下载的文件全部损坏

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

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

响应'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);
}

响应'上传文件

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。