Stream file uploaded with Express.js through gm to eliminate double write

后端 未结 1 1422
终归单人心
终归单人心 2020-12-29 00:05

I\'m using Express.js and have a route to upload images that I then need to resize. Currently I just let Express write the file to disk (which I t

相关标签:
1条回答
  • 2020-12-29 00:36

    You're on the right track by rewriting form.onPart. Formidable writes to disk by default, so you want to act before it does.

    Parts themselves are Streams, so you can pipe them to whatever you want, including gm. I haven't tested it, but this makes sense based on the documentation:

    var form = new formidable.IncomingForm;
    form.onPart = function (part) {
      if (!part.filename) return this.handlePart(part);
    
      gm(part).resize(200, 200).stream(function (err, stdout, stderr) {
        stdout.pipe(fs.createWriteStream('my/new/path/to/img.png'));
      });
    };
    

    As for the middleware, I'd copypaste the multipart middleware from Connect/Express and add the onPart function to it: http://www.senchalabs.org/connect/multipart.html

    It'd be a lot nicer if formidable didn't write to disk by default or if it took a flag, wouldn't it? You could send them an issue.

    0 讨论(0)
提交回复
热议问题