How to do upload with express in node.js

后端 未结 2 1531
灰色年华
灰色年华 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.
    '; } if(req.files.image.size > 307200) // 300 * 1024 { msg += 'File size no accepted. Máx: 300kb.
    '; } 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 = ''; } res.render('admin/upload', {layout: false, img: img, msg: msg}); })

提交回复
热议问题