Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js upload file into Buffer instead of /tmp

In a Node.js app, is it possible to upload a file (multipart/form-data) directly into a buffer on the server instead of saving the file to the filesystem?

In psuedo code you typically do this with a file upload form

router.post('/upload', function(req, res, next){
  // file is saved to /tmp/dk3idkalel4kidkek
  // do some processing on the file
  // manually save file to /www/myapp/uploads/originafilename.ext
});

Is it possible to skip the part about saving the file to /tmp and just capturing the uploaded file as a Buffer and streaming it directly to the destination directory?

An example would be uploading an image, then optimizing the image, then saving it to it's intended destination. Can you just capture the incoming stream, optimize it then save it, all without the initial saving to the /tmp directory?

like image 896
Jake Wilson Avatar asked Sep 26 '22 20:09

Jake Wilson


1 Answers

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. The memory storage engine stores the files in memory as Buffer objects. When using memory storage, the file info will contain a field called buffer that contains the entire file.

This should do exactly what you need.

You can read more here

like image 129
Gary Avatar answered Oct 11 '22 04:10

Gary