[英]Unable to upload image in MEAN-stack app
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. 现在,我从在模板中选择它开始,然后通过组件到达服务文件,在其中使用formData发出POST请求。 In the back-end I used Multer middleware to handle the upload, but something goes wrong here.
在后端,我使用Multer中间件来处理上传,但是这里有些问题。 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
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 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 这是页面+服务文件中console.logs的结果
profile.component.ts 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 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.