I am trying to use multer to handle upload of a csv file in express, then parse the file line by line. I am able to get the file as an object contained in req.body, but I am not able to parse it since it seems to now be just an object and no longer a csv string. How can I get each line from the uploaded file, individually? (app/index):
const csv = require('csvtojson');
const multer = require('multer');
const upload = multer();
router.post('/distributor/:id/upload', upload.single(), function (req, res,
next) {
req.setTimeout(600000);
console.log(req.body)
next()
}, function (req, res, next) {
//calling req.body here returns an object with \r between each line from
file, but I cannot seem to parse each line
res.end();
})
I tried to use csvtojson inside the second function, like this:
csv()
.fromString(req.body.toString(UTF8))
.subscribe((csvLine)=>{
console.log(csvLine);
}
But this just tries to parse the whole object, not each line inside of it. Here is a snippet of the object that is returned by multer:
{"UPC,Price,SKU,Title\r\n043171884536,1.17,538397,ORANGE YARN EGGS SIZE 4 -
4 PK\r\n043171080044,1.39,942227,MIKE'S YELLOW/CORN GLO
BAIT\r\n035011000046,1.98,161687,REPLACEMENT BRAKE
PADS\r\n056389001503,1.79,41582,FIRE
LIGHTERS\r\n087837005156,5.04,266320,PLATINUM GREEN 1/4LB SPOOL
25#\r\n046295070045,1.54,604652,MIKE'S GARLIC GLO-SCENT
OIL\r\n043171660161,1.02,126011,THREAD RED 100'\r"}
Edit** Before I was using bodyParser. I saw in an issue that using bodyParser with multer will not work, so I commented it out. Now, I don't get a body object, or a file object, or a files object. I tried using upload.none() and sending the same file in the request, to see if I could get it to error out with the message "LIMIT_UNEXPECTED_FILE", but it did not, so it seems multer does not even recognize that a file is being sent. I am testing this in Postman, with the content-type set to false and the body as binary with a file attached. Is there something wrong with trying to test the request that way?
In the example provided by the multer documentation, the req.body object will contain the text fields from the form, and req.file will contain the file that was uploaded:
Have you tried using the
file
object? Something like the following: