Simple way to upload image with node.js and express?

拥有回忆 提交于 2019-12-06 21:36:44

I use busboy middleware in express to parse out images in a multipart/form-data request and it works pretty nice.

My code looks something like:

const busboy = require('connect-busboy');
//...
app.use(busboy());

app.use(function parseUploadMW(req,res,next){
  req.busboy.on('file', function onFile(fieldname, file, filename, encoding, mimetype) {
    file.fileRead = [];
    file.on('data', function onData(chunk) {
      this.fileRead.push(chunk);
    });
    file.on('error', function onError(err) {
      console.log('Error while buffering the stream: ', err);
      //handle error
    });
    file.on('end', function onEnd() {
      var finalBuffer = Buffer.concat(this.fileRead);
      req.files = req.files||{}
      req.files[fieldname] = {
        buffer: finalBuffer,
        size: finalBuffer.length,
        filename: filename,
        mimetype: mimetype.toLowerCase()
      };
    });
  });
  req.busboy.on('finish', function onFinish() {
    next()
  });
  req.pipe(req.busboy);
})

Then files will be in the req object for you at req.files in your express routes.

This technique works fine for small images. If you are doing some hardcore uploading, you may want to consider streaming the files (to save memory) to their destination - like s3 or similar - which can also be achieved with busboy

Another package that is popular and also decent is: https://github.com/andrewrk/node-multiparty.

Sara Barrera Riano

Im using multer and it works perfectly. It stores your image locally. You can also send it to mongodb if you want. This is how i am doing it.

var multer  = require('multer');
var done    = false;

//define the model you are working with*
var Slides = require('./models/work');

app.use(multer({
    dest: './public/img',
    rename: function (fieldname, filename) {
        return filename+Date.now();
    },

    onFileUploadStart: function (file) {
        console.log(file.originalname + ' is starting ...')
    },

    onFileUploadComplete: function (file) {
        console.log(file.fieldname + ' uploaded to  ' + file.path);
        done = true;
        var id= file.fieldname;
        var str = file.path;
        var image = str.replace('public', '');

        var slidegegevens = {
            "id": id,
            "img": image
        };

        var s = new Slides(slidegegevens);
        s.save(function (err, slidegegevens) {
            console.log(err);
            console.log('slidegegevens: ' + slidegegevens);
        }); 
    }
}));

I think is better use formidable to handle incoming images.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!