Search code examples
javascriptnode.jsexpressfilemulter

How do I download a buffer file which is stored in memory in express.js?


Explanation: So, basically I am trying to make a express.js website where I can upload files and it gets saved in the database and users can download them later on. So, my idea was to convert the file (.jar , .txt and .json) into buffer data and store it in MongoDB. And then fetch the buffer data from MongoDB and download that file. So, I read through the docs and couldn't find anything that does this.

Code: There is nothing really to show, I have a variable which has buffer data and I am using "[email protected]".

For testing, I am currently uploading the file using multer and once I click "upload", I am trying to download the same file to save time(instead of saving and fetching from database), so the buffer data is currently stored in "req.file.buffer". When I log "req.file" , I get this

console.log(req.file)
{
  fieldname: 'fileupload',
  originalname: 'jg.txt',
  encoding: '7bit',
  mimetype: 'text/plain',
  buffer: <Buffer >,
  size: 0
}

Conclusion: I want to convert the buffer data (req.file.buffer) into a downloadable file which the user can download(later on, make it such that it can be sent as a email attachment but both of them requires a file path and name, so once I figure out how to do the express.js thing, I can do the mail thing too). I have read many articles which first saves the buffer data into a file and then uploads, but I want to do without that


Solution

  • res.set({
      "Content-Type": <content type of your file>,
      "Content-Disposition": "attachment; filename=<name of your file>"
    });
    res.end(req.file.buffer);
    

    This first sets the headers that cause the browser to download the file, then sends the file contents.

    But your req.file.buffer seems to be an empty buffer, so the upload has perhaps not worked?