【问题标题】:Res.download() working with html form submit but not an Axios post callRes.download() 使用 html 表单提交但不是 Axios 后调用
【发布时间】:2019-11-01 07:00:33
【问题描述】:

我正在编写一个小应用程序,它将来自 React 应用程序的信息提交到 Express 服务器的“/download”API,然后它将一个新文件写入本地文件系统并使用 Express 在客户端下载新创建的文件fs.writeFile() 回调中的 res.download()。

我一直在使用常规的 html 表单提交来发布数据,但由于复杂性的增加,我已经切换到使用 Axios 并且它不再工作了。

奇怪的是只有客户端的下载似乎停止了工作。编写文件工作得很好,所有控制台日志都是相同的(“文件下载!”下面的日志)。当我切换回表单提交时,它会继续工作,所以唯一的变化是使用 Axios 发送发布请求。据我所知,一旦数据到达那里,两者之间应该没有任何区别,但我希望有人比我更深入地了解这一点。

除了在表单和 Axios 发布请求之间进行测试之外,我还尝试将 Axios 请求的内容类型从“application/json”更改为“x-www-form-urlencoded”,以匹配内容输入表单发送的内容可能是答案

以下是相关应用的相关代码 sn-ps:

server.js(节点 JS)

app.post('/download', (req, res) => {
  console.log("Requst data");
  console.log(req.body.html);


  fs.writeFile("./dist/test.txt", res.body.test,
    (err) => {
      if(err) {
        return console.log(err);
      } else{
        console.log("The file was saved!");
      }

      let file = __dirname + '/text.txt';
      /*This is the issue, the file is not downloading client side for the Axios iteration below*/
      res.download(file,(err)=>{
        if(err){
          console.log(err);
        } else {
          console.log(file);
          /*This logs for both View.js iterations below*/
          console.log("File downloaded!");
        }
      });
    });
})

App.js(反应)

handleSubmit(e){
    e.preventDefault();

    axios.post(`/download`, {test: "test"})
      .then(res => {
        console.log("REQUEST SENT");
      })
      .catch((error) => {
        console.log(error);
      });
}

render(){
      return(
        <div>
          <View handleSubmit={this.handleSubmit} />
        </div>
      )
}

View.js(反应)

这行得通:

render(){
      return(
        <form action="/download" method="post">
            <input type="submit">
        </form>
      )
}

在客户端启动下载,但其他工作正常:

render(){
      return(
        <form onSubmit={this.props.handleSubmit}>
            <input type="submit">
        </form>
      )
}

我没有收到任何错误,除了客户端下载之外,一切似乎都正常运行。

预期的结果是文件在客户端使用 Axios 下载,但事实并非如此。

更新:Bump,对此没有任何吸引力

【问题讨论】:

    标签: javascript node.js reactjs http axios


    【解决方案1】:

    实际上,您可以在 Ajax POST 请求中下载文件,并进行一些 blob 操作。示例代码如下,附解释注释:

    handleSubmit(e){
      var req = new XMLHttpRequest();
      req.open('POST', '/download', true); // Open an async AJAX request.
      req.setRequestHeader('Content-Type', 'application/json'); // Send JSON due to the {test: "test"} in question
      req.responseType = 'blob'; // Define the expected data as blob
      req.onreadystatechange = function () {
        if (req.readyState === 4) {
          if (req.status === 200) { // When data is received successfully
            var data = req.response;
            var defaultFilename = 'default.pdf';
            // Or, you can get filename sent from backend through req.getResponseHeader('Content-Disposition')
            if (typeof window.navigator.msSaveBlob === 'function') {
              // If it is IE that support download blob directly.
              window.navigator.msSaveBlob(data, defaultFilename);
            } else {
              var blob = data;
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = defaultFilename;
    
              document.body.appendChild(link);
    
              link.click(); // create an <a> element and simulate the click operation.
            }
          }
        }
      };
      req.send(JSON.stringify({test: 'test'}));
    }
    

    对于后端,没有什么特别的,只是一个简单的res.download 声明:

    app.post('/download', function(req, res) {
      res.download('./example.pdf');
    });
    

    对于 axios,前端代码如下所示:

    axios.post(`/download`, {test: "test"}, {responseType: 'blob'})
      .then(function(res) {
            ...
            var data = new Blob([res.data]);
            if (typeof window.navigator.msSaveBlob === 'function') {
              // If it is IE that support download blob directly.
              window.navigator.msSaveBlob(data, defaultFilename);
            } else {
              var blob = data;
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = defaultFilename;
    
              document.body.appendChild(link);
    
              link.click(); // create an <a> element and simulate the click operation.
            }
      })
      .catch((error) => {
        console.log(error);
      });
    

    【讨论】:

      【解决方案2】:

      浏览器不会将 POST 请求的响应作为文件下载处理,因此您要么需要发出另一个请求,要么以不同的方式处理响应。

      下面是发出另一个请求的示例,在后端创建文件后去获取文件。另一个答案给出了一个很好的例子,使用 Blob API 直接处理来自 POST 请求的响应数据。

       axios.post(`/download`, {test: "test"})
        .then(res => {
          console.log("REQUEST SENT");
      
          // Send back an identifier, or whatever so that you can then
          // retrieve the file with another request. 
      
          // res.id is hypothetical, you simply need to be able to access the file
          // whether by filename, id, however you want.
          window.open("/download?id=" + res.id);
        })
        .catch((error) => {
          console.log(error);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-11
        • 2019-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-03
        • 2016-01-09
        相关资源
        最近更新 更多