简体   繁体   English

从nodejs服务器下载文件在客户端下载为损坏的文件

[英]Downloading files from nodejs server download as corrupted files on the client side

On the client side it is a react app.在客户端,它是一个反应应用程序。 I set up an endpoint that I can request the file from.我设置了一个端点,我可以从中请求文件。 However every file from pdfs, to pngs, to excel files all seem to be corrupted upon trying to download from the server, can't successfully open any of these files.但是,从 pdfs、pngs 到 excel 文件的每个文件在尝试从服务器下载时似乎都已损坏,无法成功打开这些文件中的任何一个。 Was wondering if anyone had any insight about it.想知道是否有人对此有任何见解。 Haven't been able to find anything that works.一直找不到任何有效的东西。

See below for the code for both the backend and front end.有关后端和前端的代码,请参见下文。

Backend node.js后端 node.js

ChangeLogAttachment_read(req, res, id, file_path, file_type)
                    .then(resp => {
                        res.download(file_path, file_name, (error)=>{
                            if(error) {
                                console.log("Error", error);
                            }
                        });

                        // Tried these
                        // res.contentType(file_type);
                        // res.send(fs.readFileSync(file_path));
                        // res.send(resp)
                    })

                    .catch(err => {

                        err.location = 'Error in NS_Controller.changeLogAttachments read.';
                        log.error(err)
                    });

Front end - react前端——反应

requestFile = (id, filePath, fileName , fileType)=> {
    let token = AuthUtils.getToken();

    let data = {};
    data['action'] = 'read';
    data['id'] = id;
    data['file_path'] = filePath;
    data['file_type'] = fileType;
    data['file_name'] = fileName;

    axios({
      url:  process.env.REACT_APP_HOST +
        process.env.REACT_APP_PORT + '/pbx/changelog/attachments',
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + token,
        responseType:'blob'
      },
      timeout: 10000,
      data
    }).then(response=> {
      console.log("Response", response);

      const url = window.URL.createObjectURL(new Blob([response.data]));
      // const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName); //or any other extension
      document.body.appendChild(link);
      link.click();

    }).catch(error=> {
      console.log("Error", error);
      
    })

  }

You should change response type in axios headers object to "arraybuffer"您应该将 axios 标头 object 中的响应类型更改为“arraybuffer”

headers: {
        Authorization: 'Bearer ' + token,
        responseType:'arraybuffer'
      },

Source: https://github.com/axios/axios/issues/448#issue-176993853来源: https://github.com/axios/axios/issues/448#issue-176993853

Actually was able to solve it cause the response type blob had to be outside of the headers like below:实际上能够解决它,因为响应类型 blob 必须位于标头之外,如下所示:

{
      url:  process.env.REACT_APP_HOST +
        process.env.REACT_APP_PORT + '/pbx/changelog/attachments',
      method: 'POST',
      responseType:'blob',
      headers: {
        Authorization: 'Bearer ' + token
      },
      timeout: 10000,
      data
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM