3

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?

6
  • are you getting the status from the request? Commented Jul 19, 2016 at 12:29
  • What do you mean with if status == "cancel"? Commented Jul 21, 2016 at 11:10
  • What does formData.submit(url + '/service/uploadFile/' does? Commented Jul 22, 2016 at 11:27
  • So, I'd suggest you interrupt from the client if it is a user interrupt, However, if you want to interrupt a stream based upload, simply throw an error!. Commented Jul 25, 2016 at 5:32
  • It's not clear what the OP is asking us. Commented Jul 25, 2016 at 5:40

3 Answers 3

1

If status == "cancel" try this:

req.pause()
res.status = 400;
res.end('Upload cancelled');
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.