How to do upload with express in node.js

后端 未结 2 1532
灰色年华
灰色年华 2021-02-03 16:12

My code is like this:

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


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 16:47

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

提交回复
热议问题