So I have a mean stack app. At a user's profile page I want them to be able to upload an image.
Now, I start by selecting it in the template, then through the component it reaches the service file where I make a POST request with formData. In the back-end I used Multer middleware to handle the upload, but something goes wrong here. The following is my code on the back-end.
var multer = require('multer')
var upload = multer({ dest: '../public/uploads/' });
router.post('/uploadProfilePicture/:userId', upload.single('avatar'), function(req, res){
console.log('entered');
console.log(req.file);
console.log(req.body);
res.status(200).json({
msg: 'guuud'
})
});
I mostly just want to check if I reach the back-end. The console gives me the following error:
POST /user/uploadProfilePicture/5aaf1b7c18f2aa3d88e3b59e 500 16.382 ms - 1711
There's no console log of entered and neither of the other ones. Something goes wrong between the service and the back-end, but I have absolutely no idea.
Here are the service and other files used for this upload.
Service.component.ts
postFile(fileToUpload: File, userId) {
const formData: FormData = new FormData();
console.log(fileToUpload);
formData.append('fileKey', fileToUpload, fileToUpload.name);
console.log(formData);
return this.http.post("http://localhost:3200/user/uploadProfilePicture/" + userId, formData)
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
Here is the page + the results of the console.logs in the service file
profile.component.ts
handleFileInput(files: FileList){
this.fileToUpload = files.item(0);
this.uploadFileToActivity();
}
uploadFileToActivity() {
this.userService.postFile(this.fileToUpload, localStorage.getItem('userId')).subscribe(data => {
console.log(data)
}, error => {
console.log(error);
});
}
profile.component.html
<div class="col-md-8 col-md-offset-2 profilePicSection">
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
</div>
Edit: The error my server console gives me:
Error: Unexpected field
at makeError (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-error.js:12:13)
at wrappedFileFilter (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\index.js:40:19)
at Busboy.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\multer\lib\make-middleware.js:114:7)
at Busboy.emit (events.js:159:13)
at Busboy.emit (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\main.js:38:33)
at PartStream.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\busboy\lib\types\multipart.js:213:13)
at PartStream.emit (events.js:159:13)
at HeaderParser.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:51:16)
at HeaderParser.emit (events.js:159:13)
at HeaderParser._finish (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:68:8)
at SBMH.<anonymous> (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:40:12)
at SBMH.emit (events.js:159:13)
at SBMH._sbmh_feed (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:159:14)
at SBMH.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\streamsearch\lib\sbmh.js:56:14)
at HeaderParser.push (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\HeaderParser.js:46:19)
at Dicer._oninfo (C:\Users\TijlD\Desktop\test\moviemeter\node_modules\dicer\lib\Dicer.js:197:25)
I use this code for video type files and it works fine, Hope it helps you
var storage = multer.diskStorage({
destination: function (req, file, callback) {
var fileDest = path.join('../uploads/');
if (!fs.existsSync(fileDest)) {
mkdirp(fileDest, function (err) {
if (err) {
logger.error(err);
callback(err, false);
} else {
callback(null, '../uploads');
}
});
} else {
callback(null, '../uploads/');
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '.' + file.originalname.split('.')[1]);
}
});
var upload = multer({
storage: storage,
fileFilter: function (req, file, callback) {
// To reject this file pass `false`, like so:
var sw = 0;
for (var i = 0; i < config.videoMimeTypes.length; i++) {
if (file.mimetype === config.videoMimeTypes[i]) {
sw = 1;
break;
}
}
if (sw === 0) {
logger.error('Not allowed file type sent');
// return callback(new Error('Only video files are allowed!'));
return callback('Only video files are allowed!', false);
}
// To accept the file pass `true`, like so:
callback(null, true);
},
limits: {
fileSize: config.maxUploadSize
}
});
app.post('/upload', upload.any(), router.uploader);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.