Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop request during file upload in NodeJs

I'm write an image uploader, and I want to constrain the size of the image to under 3mb. On the server side, I can check the size of the image in the header, something like this (using express):

app.post('/upload', function(req, res) {
  if (+req.headers['content-length'] > 3001000) { // About 3mb
     // Do something to stop the result
     return res.send({'error': 'some kind of error'});
  }
  // Stream in data here...
}

I tried to stop the req by (and permuations of)

req.shouldKeepAlive = false;
req.client.destroy();
res.writeHead(200, {'Connection': 'close'});
res.end()

None of them really "destroys" the request to prevent more data being uploaded. req.client.destroy() seem to freeze the download, but the res.send({error... is not being sent back.

Help!

like image 688
foobar Avatar asked May 01 '26 17:05

foobar


1 Answers

Throw an error and catch it. It will stop the file upload, allowing you to send a response.

try { throw new Error("Stopping file upload..."); } 
catch (e) { res.end(e.toString()); }

It's a bit hackish, but it works...

like image 164
mendezcode Avatar answered May 03 '26 10:05

mendezcode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!