我在前端使用 Angular 5,在后端使用 Node,并使用 Mongo 作为数据库。现在我试图将图像保存到数据库,但不断收到此错误。我不知道我是在正面还是背面犯了错误,因为这是我第一次处理文件。我做了我的研究,但它主要指向 Angular 1.x。
HTML组件
<form [formGroup]="form" (ngSubmit)="onSubmitPhoto()">
<div class="form-group">
<input type="file" class="form-control" formControlName="photo">
</div>
<button class="btn btn-default" type="submit">Sačuvaj</button>
</form>
TS组件
onSubmitPhoto() {
this.profile.photo = this.form.value.photo;
this.usersService.updatePhoto(this.profile, this.id)
.subscribe(
data => {
this.router.navigateByUrl('/');
},
error => console.error(error)
);
}
Service
updatePhoto(profile: Profile, id: string) {
const body = new FormData();
body.append('photo', profile.photo);
const headers = new Headers({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:3000/profile/photo/' + id, body, { headers: headers })
.map((response: Response) => response.json())
.catch((error: Response) => {
return Observable.throw(error.json());
});
}
Node.JS
router.post('/photo/:id', (req, res) => {
console.log(req.files);
User.find({ _id: req.params.id })
.exec((err, user) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
user.img.data = fs.readFileSync(req.files);
user.img.contentType = 'image/png';
user.save((err, obj) => {
if (err) {
throw err
}
console.log('success')
})
});
});
Model
const schema = new Schema({
img: { data: Buffer, contentType: String}
});
module.exports = mongoose.model('User', schema);
任何帮助表示赞赏。
此外,记录 req.files 返回未定义。