User2682
User2682

Reputation: 213

Reading buffer data from uploaded file in NodeJS

I am uploading a file using 'express' module. I have to read the EXIF data of the uploaded image using node-exif. I do not want to store the file on disk and the above module support reading EXIF data from buffer. I need to read the buffer data from the uploaded image. Here is the upload code:

var express = require('express');
var app = express();
var fs = require('fs');
var multiparty = require("multiparty");

module.exports.UploadImage = function (req, res, next) {
    // Handle request as multipart  
    if (!req.files)
        return res.status(400).send('No files were uploaded.');  

    var sampleFile = req.files.uploadedFile;
    //Here I need to have the buffer.
    res.send('Done!');
}

Can someone help me getting the buffer data as I am very new to Node universe?

Upvotes: 3

Views: 12955

Answers (2)

Darkhan ZD
Darkhan ZD

Reputation: 610

Here is how you can get buffer:

var express = require("express");
const fileUpload = require('express-fileupload');
var app = express();
app.use(fileUpload());

app.post("/upload", (req, res) => {

   console.log(req.files.file);

   res.status(200).send('Success!!!');
});

The console output:

{
  name: 'task.txt',
  data: <Buffer ef bb bf 37 38 37 39 34 38 36 34 0d 0a 37 38 37 39 ... 57 more bytes>,
  size: 107,
  encoding: '7bit',
  tempFilePath: '',
  truncated: false,
  mimetype: 'text/plain',
  md5: '6e37e5195b2acfcac7713952ba080095',
  mv: [Function: mv]
}

The data paramerter is what you need. You can parse the buffer into string as follow:

   console.log(req.files.file.data.toString('utf8'));

Upvotes: 3

Manjunath Reddy
Manjunath Reddy

Reputation: 1197

I think this is what you are looking for

  module.exports.UploadImage = function (req, res, next) {
    // Handle request as multipart  
    if (!req.files)
        return res.status(400).send('No files were uploaded.');  

    var sampleFile = req.files.uploadedFile;
    //Here I need to have the buffer.
    var chunks = []
    req.on('data', function (chunk) {
        // reads chunks of data in Buffer
        console.log(chunk) // Prints <Buffer 8a 83 ef ... >
        chunks.push(chunk)
    })

    res.send('Done!');
  }

Upvotes: 0

Related Questions