Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js: How to download a file using POST request

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:

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

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

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

like image 694
wdetac Avatar asked Apr 20 '15 09:04

wdetac


1 Answers

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 - See EDIT below for updated client code
$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.

*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
like image 163
avn Avatar answered Oct 19 '22 22:10

avn