Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a ReadStream from memoryStorage with multer

Tags:

node.js

multer

I upload a file to my API using multer:

const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
      fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
})

The file appears in const file = req.files["my_file_name"][0]

Now I want to create a readStream for this like so:

fs.createReadStream(file.path).pipe(stream);

The problem is, file.path is undefined when I'm using memoryStorage() with multer. How can I make this work with memoryStorage?

like image 403
Tometoyou Avatar asked Jan 29 '19 11:01

Tometoyou


People also ask

What is DiskStorage in multer?

DiskStorage. The disk storage engine gives you full control on storing files to disk. const storage = multer. diskStorage({ destination: function (req, file, cb) { cb(null, '/tmp/my-uploads') }, filename: function (req, file, cb) { const uniqueSuffix = Date.

How do I upload a node js file to multer?

The following code will go in the app.const multer = require('multer'); const upload = multer({dest:'uploads/'}). single("demo_image"); Here, we have called the multer() method. It accepts an options object, with dest property, which tells Multer where to upload the files.

Where does multer save file?

Before using Multer to handle the upload action of files, we need to understand a few things. The actual files are never stored in the database. They are always stored someplace on the server. In our tutorial, we will store the uploaded files in the public folder.

What does multer return?

multer(). single() returns a middleware function that expects to be called with the arguments (req, res, callback) . It can be called automatically as middleware as in: app.


1 Answers

When using memoryStorage you will not get file.path, Your file will be in buffer on your request.

req.file will have information { fieldname, originalname, encoding, mimetype, buffer }

Output Stream on Console

const streamifier = require('streamifier');
streamifier.createReadStream(req.file.buffer).pipe(process.stdout);

Read & Write Stream as File

const streamifier = require('streamifier');
var writeStream = fs.createWriteStream('./uploads/test.png');
streamifier.createReadStream(req.file.buffer).pipe(writeStream);

Reference : File information

like image 109
Şivā SankĂr Avatar answered Nov 08 '22 19:11

Şivā SankĂr