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

wde*_*tac 6 javascript node.js express

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

1.

app.post("/download", function (req, res) {
    res.download("./path");
});
Run Code Online (Sandbox Code Playgroud)

2.

app.post("/download", function (req, res) {
    res.attachment("./path");
    res.send("ok");
});
Run Code Online (Sandbox Code Playgroud)

3.

app.post("/download", function (req, res) {
    res.sendFile("./path");
});
Run Code Online (Sandbox Code Playgroud)

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

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

avn*_*avn 11

这可能不是你想要的,但我遇到了同样的麻烦.这就是我最后所做的:

  • 客户
$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');
  });
Run Code Online (Sandbox Code Playgroud)
  • 服务器
// 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");
});
Run Code Online (Sandbox Code Playgroud)

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

*编辑: 客户端代码不准确,经过一些测试后发现我只需要在客户端上执行以下操作:

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