Express js: how to upload a file using a POST request

When I use GET everything works fine. However, I try to use POST to achieve the same effect. Here is the code I 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 right way to do this?

EDIT: I am sending a POST request via an HTML form to /download. ./pathis a static file. When I use the code in method 1, I can see the correct response header and response body in the developer tool. But the browser does not request a download.

+4
source share
1 answer

It may not be exactly what you want, but I have the same problem. Here is what I did at the end:

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

, $window.open(/download); HTML? , . XHR, , .

* EDIT: , , , :

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

All Articles