Simple way to upload image with node.js and expres

2019-06-02 03:59发布

I've found few articles explaining the process but most of them are not up do date. How do you handle image upload in node.js?

3条回答
手持菜刀,她持情操
2楼-- · 2019-06-02 04:29

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.

查看更多
forever°为你锁心
3楼-- · 2019-06-02 04:40

I think is better use formidable to handle incoming images.

查看更多
Summer. ? 凉城
4楼-- · 2019-06-02 04:41

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);
        }); 
    }
}));
查看更多
登录 后发表回答