Taylor Johnson
Taylor Johnson

Reputation: 484

Using Multer - How do I read an uploaded file (text/.csv)

First time using Multer - I built an app to parse a .csv file and count the # of occurences of each keyword and phrase in the file, but I made changes using node and express to parse the file AFTER it's been submitted via a form using express router and multer.

I'm a bit confused as I am no longer reading a File but this:

{
[💻]   fieldname: 'file-upload',
[💻]   originalname: 'Google-Analytics.csv',
[💻]   encoding: '7bit',
[💻]   mimetype: 'text/csv',
[💻]   buffer: <Buffer 48 65 61 64 65 72 2c 53 75 62 2d 68 65 61 64 65 72 2c 54 61 67 2c 4b 65 79 77 6f 72 64 73 2c 54 65 73 74 69 6d 6f 6e 69 61 6c 0d 0a 54 75 72 6e 20 69 ... >,
[💻]   size: 2990
}

I think I need to find something to process the buffer as Jimp processes an image upload from multer.

TL;DR; How do I read the text file contents when uploading with multer?

Upvotes: 11

Views: 27940

Answers (4)

Raj Gohel
Raj Gohel

Reputation: 1102

Append extension of uploaded file with the file name.

filename: function (req, file, cb) {
console.log("File Object",file);
let ext = '';
if(file.originalname.split('.').length >1 ){
ext = file.originalname.substring(file.originalname.lastIndexOf('.'));
}
console.log('ext', ext);
cb(null, file.fieldname + '-' + Date.now() + ext)
}

Upvotes: 0

Amaranadh Meda
Amaranadh Meda

Reputation: 724

I hope below answer will resolve your problem.

Add

app.use(multer({
  dest: 'uploads/'
}));

after

app = express(); 

In the request handler you can access file details as below

 req.files 

For example in the input field name is "test". You can access file details as below.

req.files.test
req.files.test.path

will give you exact path of the file.

So you can use

let data = fs.createReadStream(req.files.test.path,'utf8');

then you can take a look at

console.log(data);

Upvotes: 13

JoshuaTree
JoshuaTree

Reputation: 1261

An alternative is the access the multer file Buffer object directly.

Calling to string on this object will try and parse out the string in UTF-8 by default.

eg: bufferByteArray.toString();

https://nodejs.org/api/buffer.html

Upvotes: 3

Tom Mendelson
Tom Mendelson

Reputation: 625

When you configure Multer you should assign what is the destionation of the uploaded file

something like this:

var upload = multer({ dest: 'uploads/' })

then, you can just read the file from storage with node file system

Upvotes: 4

Related Questions