2

I'm going to upload a file using nodejs with express.

I see that bodyParser gets the job done...

app.use(express.bodyParser({"limit": '2mb'}));

But if I want to limit the size of the request I found that it doesn't cancel the upload somehow. The client keeps sending data.

So I wrote this middleware:

app.use(function (err, req, res, next) {

   if(err.status == 413){
       req.destroy();
       return res.json({
            "status": 413,
            "message": err
       },413);
   }else
       next(err);
});

It works, cancels the upload but the client doesn't get (or ignore) the response!

I think this could be a behavior of the http protocol, so any help is appreciated.

Jayant Bhawal
  • 2,044
  • 2
  • 31
  • 32
RLeite
  • 21
  • 3

1 Answers1

0

I think that your code should work, but don't destroy the request! Just delete req.destroy(); line from your code. You can also try something like this (it was working on my side) in order not to use middleware:

express = require 'express'
app = express()
swig = require 'swig'
cons = require 'consolidate'
swig.init {
  root: __dirname + '/views'
  allowErrors: true
}
app.set 'views', __dirname + '/views'
app.set 'view options', {layout: false}
app.engine '.html', cons.swig
app.set 'view engine', 'html'

# set upload dir
app.use express.bodyParser {uploadDir: './upload'}

app.get '/', (req, res) ->
  res.render 'index.html', {}

app.post '/file-upload', (req, res) ->
  # you can get some info about files here (size, path, name, type)
  console.log req.files
  # check that size is good
  if req.files.thumbnail.size > 200
    res.send 413
  else
    res.send 'Uploaded!'

console.log 'listen port 3000'
app.listen 3000

And in form:

<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="file" name="thumbnail">
<input type="submit">
</form>

Look here for details. Hope this will help you.

Peter Gerasimenko
  • 1,906
  • 15
  • 13
  • That works... but my problem is when the file is too big... I don't want to wait until the file is completely uploaded to reject it. – RLeite Jan 07 '13 at 09:56
  • You can look [here](http://stackoverflow.com/questions/1601455/check-file-input-size-with-jquery) and [here](http://forum.jquery.com/topic/checking-file-size-before-uploading-it) but you'll have problems in IE. Of course you should check file size on server too. – Peter Gerasimenko Jan 07 '13 at 11:44