Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 643
Chris Johnson Avatar asked Mar 13 '18 14:03

Chris Johnson


3 Answers

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);
like image 162
Amaranadh Meda Avatar answered Nov 04 '22 15:11

Amaranadh Meda


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

like image 44
Tom Mendelson Avatar answered Nov 04 '22 14:11

Tom Mendelson


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

like image 2
JoshuaTree Avatar answered Nov 04 '22 14:11

JoshuaTree