1

EDIT: Edited it using Mikhail's suggestion. Got closer to the solution

Hi I am trying to upload a JSON file using nodejs but for some reason it says my file is undefined. A file appears in my Public folder that contains the contents of the uploaded file however. I was wondering if someone would be able to help me out. Thanks

Here is the HTML

<form method="post" enctype="multipart/form-data" action="/file-upload"> <input type="file" name="theFile" > <input type="submit" class = "submit"> </form> 

EDIT: Here is the server.js

 app.post('/testtwilio',upload.single('theFile'),function(req, res, next) { console.log('FIRST TEST: ' + req.file); }); 

Here is the JSON file

[{"name":"FIRST LAST","date":"12/22/2016","number":"7523924324"}] 

Here is what is being logged

FIRST TEST: [object Object] 
6
  • Try with console.log( req); or console.log(req.files); for debugging purpose. Commented Aug 7, 2016 at 1:54
  • Have you set up multer? Commented Aug 7, 2016 at 1:55
  • EDIT: with req it says [object Object] and with req.files it says undefined Commented Aug 7, 2016 at 1:55
  • and I haven't set multer up, is that required? Commented Aug 7, 2016 at 1:56
  • i tried it with multer but getting the same error Commented Aug 7, 2016 at 2:18

2 Answers 2

3

Change your JSON.stringify(req.files) to JSON.stringify(req.file)

Full code

HTML

<form id = "uploadForm" enctype = "multipart/form-data" action = "/api/file" method = "post"> <input type="file" name="userFile" /> <input type="submit" value="Upload File" name="submit"> </form> 

JS

var express = require('express') var multer = require('multer') var upload = multer({ dest: 'uploads/' }) var app = express() app.get('/',function(req,res){ res.sendFile(__dirname + "/index.html"); }); app.post('/api/file', upload.single('userFile'), function (req, res, next) { console.log(JSON.stringify(req.file)) }) app.listen(3000,function(){ console.log("Working on port 3000"); }); 

Note:

File name which you use in multer.single() method should match name in input <input type="file" name="userFile" />

Sign up to request clarification or add additional context in comments.

4 Comments

I did that and it returned [object Object].
@Nik it's strange, because I have experienced the code before answer to your question, and with your JSON file [{"name":"FIRST LAST","date":"12/22/2016","number":"7523924324"}] all should work
@Nik You need to get contents of the file after upload ?
I got it to work finally! Thanks so much for taking the time to record a video, I really appreciate it.
1

If you use the .single(...) method the file will be in req.file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.