javascript - 表达 js : How to download a file using POST request

标签 javascript node.js express

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

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");
});

它们都不起作用。执行此操作的正确方法是什么?

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

最佳答案

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

  • 客户端 - 请参阅下面的编辑以获取更新的客户端代码
$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');
  });
  • 服务器
// 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");
});

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

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

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

关于javascript - 表达 js : How to download a file using POST request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29743395/

相关文章:

javascript - (!~index) 比 (index === -1) 快吗?

在 Ubuntu 上无法从外部 IP 访问 Node.js

javascript - JWT 不解码 "JWT malformed"- Node Angular

node.js - 读取 MIFARE Classic 卡的第二个扇区及更多扇区时出现错误 6800

javascript - 如何使用window.location防止不断刷新 Angular 页面

javascript - 92% block Assets 优化 - webpack

c# - 如何使用javascript将文本框数据保存到文件

arrays - 当满足某些条件时,从该对象数组中删除对象

node.js - 使用 CouchDB 插入非常慢?

express - Nginx 上游到 Express 服务器 - 502 错误