如何从Node.js服务器发送多个文件以响应客户端

时间:2020-07-08 21:46:47

标签: node.js reactjs axios

嗨,我想从Node JS服务器发送各种不同的文件,以响应客户端以能够在页面上加载。我以前可以使用fs.readFile发送单个图像,但是我试图将其应用于多个文件(可以是图像/ pdf /其他文件类型),但是似乎回传了一些数据,该数据类型甚至是应用程序json在前端时,我已指定responseType:'blob'。在该函数中,我在数据库中查询文件路径,然后从那里尝试读取文件并将其发送到数组中。我不确定我是否会以正确的方式处理问题,有人可以推荐一种更好的方法。

//serverside

readChangelogAttachements (req, res) {

        let body = req.method === 'POST'? req.body: req.query;
    
        let files = []

        db.generalQuery(`Example query`, (resp) => {

            //ERROR
            if (!resp.success) {

                resp.location = 'Error in attachements';
                log.error(resp);
                return res.status(resp.status).json(resp);
            }
            else {
                console.log("Attachemnts" , resp.data)
                resp = resp.data;

                for(let i = 0; i<resp.length; i++) {
                    fs.readFile(resp[i].file_path, (err, data)=> {
                        files.push(data);
                    })
                }

               
            }
        });


        res.send({
            success:true,
            files,
            id: body.id
        })

    }


//client side 

requestAttachements = (id)=> {
    let params = {
      id
    }

    console.log("ID", id);

    axios({
      url: /fake/example/attachements',
      method: 'GET',
      headers: {
        Authorization: 'Bearer ' + token
      },
      responseType:'blob',
      timeout: 10000,
      params
    }).then((response)=>{

      console.log("REQUEST ATTACHMENT", response);

      //Fill row with images

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

  }


0 个答案:

没有答案