How to do upload with express in node.js

后端 未结 2 1538
灰色年华
灰色年华 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:23

    I have a function in my project that loads files, might help you a bit:

    var app = express.createServer(
        express.bodyParser({uploadDir: "public/files", keepExtensions: true})
      , express.cookieParser()
      , express.session({ secret: 'keyboard cat' })
    );
    
    app.post('/upload', function (req, res) {
    var msg = '';
    var img = '';
    
    //console.log("type: "+req.files.image.type);
    //console.log("size: "+req.files.image.size);
    
    if(req.files.image.type != 'image/png' && req.files.image.type != 'image/jpeg' && req.files.image.type != 'image/gif')
    {
        msg = 'Invalid format, accepts only: jpg, png and gif.<br/>';
    }
    
    if(req.files.image.size > 307200) // 300 * 1024
    {
        msg += 'File size no accepted. Máx: 300kb.<br/>';
    }
    
    if(msg == '')
    {
        if(diff > 0)
        {
            name = name.substring(name.length-diff, name.length);
        }
    
        var date = new Date();
        var name = req.files.image.name;
        var diff = name.length - 20;
        var rnd_number = Math.floor(Math.random()*101);
        var new_name = date.format('yyyymmdd_HHMMssl_') + rnd_number +'_'+ name;
    
        fs.renameSync(req.files.image.path, 'public/files/img'+new_name);
    
        img = '<img src="public/files/img/'+new_name+'" width="100%"/>';
    }
    
    res.render('admin/upload', {layout: false, img: img, msg: msg});
    
    })
    
    0 讨论(0)
  • 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");
        });
    })
    
    0 讨论(0)
提交回复
热议问题