Express js:如何使用POST请求下载文件 [英] Express js: How to download a file using POST request

查看:636
本文介绍了Express js:如何使用POST请求下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用GET,一切都正常。但是,我很难使用POST实现相同的效果。以下是我尝试过的代码:

When I use GET, everything works fine. However, I struggle to use POST to achieve the same effect. Here are the code I have tried:

1。

app.post("/download", function (req, res) {
    res.download("./path");
});

2。

app.post("/download", function (req, res) {
    res.attachment("./path");
    res.send("ok");
});

3。

app.post("/download", function (req, res) {
    res.sendFile("./path");
});

它们都不工作。这样做的正确方法是什么?

None of them work. What is the correct way to do this?

编辑:
我通过HTML表单向 / download ./ path 是一个静态文件。当我在方法1中使用代码时,我可以在开发者工具中看到正确的响应头和响应体。但是浏览器不会提示下载。

I submit a POST request through a HTML form to /download. ./path is a static file. When I use code in method 1, I can see the correct response header and response body in the developer tool. But the browser does not prompt a download.

推荐答案

这可能不是你想要的,但是我一直都是这样麻烦。
这是我最后所做的:

This might not be exactly what you want, but I have been having the same trouble. This is what I did in the end:


  • 客户端

  • Client
$http.post('/download', /**your data**/ ).
  success(function(data, status, headers, config) {
    $window.open('/download'); //does the download
  }).
  error(function(data, status, headers, config) {
    console.log('ERROR: could not download file');
  });






  • em>

  • // Receive data from the client to write to a file
    app.post("/download", function (req, res) {
        // Do whatever with the data
        // Write it to a file etc...
    });
    
    // Return the generated file for download
    app.get("/download", function (req, res) {
        // Resolve the file path etc... 
        res.download("./path");
    });
    

    或者,您刚刚尝试调用 $ window.open(/ download); 从HTML?这是我的下载没有开始的主要原因。它在XHR中返回,我可以看到数据,但也没有提示下载。

    Alternatively, have you just tried calling $window.open(/download); from the HTML? This was the main reason why my download did not start. It returned in the XHR and I could see the data, but also did not prompt a download.

    *编辑:
    客户端代码不准确,经过一些更多的测试,原来我只需要在客户端执行以下操作:

    * The client code was not accurate, after some more testing it turned out that I only needed to do the following on the client:

    // NOTE: Ensure that the data to be downloaded has 
    // already been packaged/created and is available
    $window.open('/download'); //does the download
    

    这篇关于Express js:如何使用POST请求下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆