'File upload with multer returning undefined
I'm currently trying to implement file-uploads for my application, in which I use ReactJS, node.js with express, and MongoDB and mongoose. I'm using multer middleware for fileuploads, however, despite looking at all similar questions here on SO and also looking it up, I can't seem to get it to work.
This is my React form:
addUser (event) {
var formfile = new FormData();
formfile.append("file", this.state.filesToBeSent);
axios.post('adduser',
JSON.stringify({
entry: this.state.currname,
passwrd: this.state.currpasswrd,
formfile : formfile
}), {
headers: {"Content-Type": "application/json"}
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onSubmit={this.addUser} encType="multipart/form-data" >
<input value={this.state.currname} />
<input value={this.state.currpasswrd} />
<input type="file" value={this.state.filesToBeSent} name="file" />
<button type="submit" >Add</button>
</form>
);
}
This is my node.js file:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = require('../models/User.js');
var bodyParser = require('body-parser');
var multer = require("multer");
const uuidv4 = require("uuid/v4");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cd(null, "./uploads");
},
filename: (req, file, cb) => {
const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, newFilename);
},
})
const upload = multer({ storage });
router.post("/", upload.single("file"), (req, res) => {
console.log(req.file + " and exit.");
});
module.exports = router;
I'm not doing anything with the text-inputs just yet, because I wanted to get the file upload to work first.
I tried out a variety of things, like using async(req, res) in router.post(). I tried using x-www-form-urlencoded as content-type and to only send the file without text-inputs( I specified formfile as data to be sent without the whole JSON.stringify(), however, I didn't manage to get it to work.
Can anyone spot a mistake in my code? Or does anyone have any other ideas about how to get it to work?
Edit: Setting up the adduser-route in app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var adduser = require('./routes/adduser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/adduser', adduser);
Solution 1:[1]
Did you test your post endpoint? You can use a rest client such as Postman or Insomnia just to make sure that this is not the problem. Send a POST request to the endpoint and see if it gets invoked.
Then I guess you should use "/adduser" on your client and not "adduser" if you endpoint is exposed at "localhost:port/adduser". Your code doesn't show how you set up the route in the node.js code.
Finally you may want to use an higher level component to perform the upload, which can handle multipart for you in case you upload larger files. I found the combination react-dropzone + Multer being quite convenient.
Solution 2:[2]
try this :
router.post("/", upload.single("formfile"), (req, res) => {
console.log(req.formfile + " and exit.");
});
Solution 3:[3]
i think the headers should be:
{"Content-Type": "multipart/form-data"}
instead of application/json.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Felipe |
| Solution 2 | Saurabh Mistry |
| Solution 3 | Aditi Ranjan |
