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
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With