Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do upload with express in node.js

My code is like this:

app.configure(function () {
    app.use(express.static(__dirname + "/media"));
    app.use(express.bodyParser({
          keepExtensions: true
    }));
})

app.post('/upload', function (req, res) {
    console.log(req.files);

    res.send("well done");
    return;
})

ant do some job like:

1.Do someting on the progoress event, how can I bind handler to the progress, complete event, I have tried req.files.on('progress', fn), but it doesn't work

2 I know how to use req.files to get the file's imformation, but how can I limit the upload file's size before it upload, or limit the upload image resolution?

like image 610
hh54188 Avatar asked Aug 31 '26 06:08

hh54188


1 Answers

You should look at multipart middleware documentation, this is the one involved in file uploading.

It says that the limit is set via the "limit" option and that progress could be listened to if you put "defer" option to true. In that case the form used by the upload is set as an attribute of your request. Then you will be able to listen to the progress event.

So your code should look like this (not tested yet):

app.configure(function () {
    app.use(express.static(__dirname + "/media"));
    app.use(express.bodyParser({
          keepExtensions: true,
          limit: 10000000, // 10M limit
          defer: true              
    }));
})

app.post('/upload', function (req, res) {
    req.form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(((bytesReceived / bytesExpected)*100) + "% uploaded");
    });
    req.form.on('end', function() {
        console.log(req.files);
        res.send("well done");
    });
})
like image 100
Frank Avatar answered Sep 02 '26 20:09

Frank



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!