Multer: How to get the file stream output and save as Buffer

Created on 12 Mar 2020  路  3Comments  路  Source: expressjs/multer

Hi,

I am trying to upload file as Buffer type and save to mongodb.

I am trying out 2.0.0-rc1 and this is roughly what I did but couldn't get it work.

const getBuffer = (filePath) => {
  const fileBuffer = [];
  const fileStream = fs.createReadStream(filePath);

  fileStream.on('data', (chunk) => {
    console.log('testend'); < not get called
   fileBuffer.push(chunk);
  }
  fileStream.once('end', () => {
   console.log('testend'); < not get called
   buffer = Buffer.concat(buffer);
  });
  console.log(buffer); < result is empty array
}

multer.array(files),
(req, res, next) => {
  const xList = req.files.map((file) => {
    fileName: file.originalName,
    // more fields
    data: getBuffer(file.path);
  });
}

This is the behavior I have..

I printed the file object, and the info are there
The path is pointed to C:\Users\me\AppData\Local\Temp\YAKSU
When I try to print some stuff within the fileStream.on('data') and fileStream.on('end'), I don't see in my console.

Also, have this error output.

Error: EPERM: operation not permitted, open C:\Users\me\AppData\Local\Temp\YAKSU

What am I doing wrong?

Thanks!

question

Most helpful comment

await getStream.buffer(file.stream) is correct, sorry, I didn't see that you specified that you were using 2.x 鈽猴笍

All 3 comments

Waiting for the stream is an asynchronous operation, something like this should work:

const getStream = require('get-stream').buffer

// ...

async (req, res, next) => {
  const xList = await Promise.all(req.file.map(async (file) => ({
    fileName: file.originalName,
    // more fields
    data: await getBuffer(file.path)
  }))
}

Based on the get-stream example, it first create the stream fs.createReadStream(filepath) then return the buffer from the stream.

const stream = fs.createReadStream('unicorn.txt');
await getStream(stream);

Is there any difference if I were to use the stream from the file object directly, where the file object is the one from multer

async (req, res, next) => {
  const xList = await Promise.all(req.file.map(async (file) => ({
    fileName: file.originalName,
    // more fields
    data: await getStream.buffer(file.stream)
  }))
}

I tested that it works with my 2nd method, but I'm not sure if I'm doing the right

await getStream.buffer(file.stream) is correct, sorry, I didn't see that you specified that you were using 2.x 鈽猴笍

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kiwenlau picture kiwenlau  路  4Comments

edi picture edi  路  4Comments

samipjain picture samipjain  路  4Comments

Gabxi picture Gabxi  路  3Comments

NobleUplift picture NobleUplift  路  4Comments