Sumit Aggarwal
Sumit Aggarwal

Reputation: 841

How to interrupt while uploading the file in node.js?

I have a code in controller like below:

BASE.APP.post('/uploadFile/:request/:file', function(req, res, next) {

  var url = req.usersession.webipAddress;

  var path = 'uploads/' + req.params.file;

  var formData = new BASE.FormData();
  formData.append('fileNameUnique', req.params.file);
  formData.append('file', BASE.FS.createReadStream(path));
  //  console.log(formData);


  formData.submit(url + '/service/uploadFile/', function(err, response) {
    // console.log(response.statusCode);
    res.send(response.statusCode);

  });
});

I want to interrupt file upload if status == "cancel", is that possible?

Upvotes: 3

Views: 574

Answers (3)

poida
poida

Reputation: 3599

Save the value returned from formData.submit and use that as a handle to call request.abort on.

E.g.

BASE.APP.post('/uploadFile/:request/:file', function(req, res, next) {     

  var formData = new BASE.FormData();
  // ...

  var formSubmitRequest = formData.submit(url + '/service/uploadFile/', function(err, response) {
    res.send(response.statusCode);
  });

  statusChanger.on('status-change', function(status) {
    if (status === "cancel" && formSubmitRequest) {
      formSubmitRequest.abort();
      res.send(524);
    }
  });

}

From https://github.com/form-data/form-data:

For more advanced request manipulations submit() method returns http.ClientRequest object

From https://nodejs.org/api/http.html#http_request_abort:

request.abort()#

Added in: v0.3.8

Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.

Upvotes: 0

Iceman
Iceman

Reputation: 6145

I don't know much about the way your code works or your workflow. This is a generic soln that most likely will work. Add more code in the question if you want a more specific soln.

try {
    if (status === 'cancel') {
        throw new Error("Stopping file upload...");
    }
} catch (e) {
    res.end("the upload was cancelled because of error: " + e.toString());
}

Upvotes: 1

Andrei Dolhescu
Andrei Dolhescu

Reputation: 49

If status == "cancel" try this:

req.pause()
res.status = 400;
res.end('Upload cancelled');

Upvotes: 1

Related Questions