javascript Express js:如何使用 POST 请求下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29743395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:59:36  来源:igfitidea点击:

Express js: How to download a file using POST request

javascriptnode.jsexpress

提问by wdetac

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:

当我使用 GET 时,一切正常。但是,我很难使用 POST 来达到相同的效果。这是我尝试过的代码:

1.

1.

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

2.

2.

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

3.

3.

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

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

他们都没有工作。这样做的正确方法是什么?

EDIT: I submit a POST request through a HTML form to /download. ./pathis 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.

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

回答by avn

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');
  });
  • Server
  • 服务器
// 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");
});

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.

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

*EDIT: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