Express js:如何使用POST请求下载文件
当我使用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表单提交POST请求/download
。 ./path
是一个静态文件。 当我在方法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"); });
或者,你刚刚尝试调用$window.open(/download);
从HTML? 这是我的下载没有开始的主要原因。 它在XHR中返回,我可以看到数据,但也没有提示下载。
*编辑:客户端代码是不准确的,经过一些更多的testing后,事实certificate,我只需要在客户端上执行以下操作:
// NOTE: Ensure that the data to be downloaded has // already been packaged/created and is available $window.open('/download'); //does the download