【问题标题】:Express js: How to download a file using POST requestExpress js:如何使用 POST 请求下载文件
【发布时间】:2015-06-26 21:55:22
【问题描述】:

当我使用 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 是一个静态文件。当我使用方法一中的代码时,我可以在开发者工具中看到正确的响应头和响应体。但是浏览器不提示下载。

【问题讨论】:

  • 哪个版本的 express js。你正在用吗。 res.download() 使用 res.sendFile() 传输文件。从 Express v4.8.0 开始也支持 res.sendFile()。
  • @Pinal 这个问题似乎与我提到的 POST 方法无关。
  • @hitman4890 我正在使用节点 v0.10.32 并表示 v4.12.3
  • 能否显示调用方法或下载请求在哪里生成的代码?还有path是正确的吗?

标签: javascript node.js express


【解决方案1】:

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

  • 客户端 - 请参阅下面的编辑以获取更新的客户端代码
$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

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    相关资源
    最近更新 更多