我在前端上使用Angular 5,后端上的节点为数据库。现在,我试图将图像保存到数据库中,但会不断遇到此错误。我无法弄清楚我是在正面还是后背犯错,因为这是我第一次使用文件。我进行了研究,但主要指向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)
);
}
服务
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')
})
});
});
模型
const schema = new Schema({
img: { data: Buffer, contentType: String}
});
module.exports = mongoose.model('User', schema);
任何帮助将不胜感激。另外,凸req.files返回未定义。
要上传文件,您需要将其包裹在FormData
实例中,如下所示:
interface Profile {
photo: File;
}
updatePhoto(profile: Profile, id: string) {
const body = new FormData();
body.append('photo',profile.photo);
return this.http.post(`http://localhost:3000/profile/photo/${id}`, body,)
.map((response: Response) => response.json())
.catch((error: Response) => {
return Observable.throw(error.json());
});
}
此外,您的后端很可能在以下部分失败:
user.img.data = fs.readFileSync(req.body.photo);
考虑到您现在正在使用multipart/form-data
编码上传表单,您将需要使用一些中间件来解析后端中的请求,如expressjs doc
您可以使用Multer或Express-Fileupload
如果您选择第二个,则需要以下内容:
const fileUpload = require('express-fileupload');
router.use(fileUpload());// use express-fileupload as default parser for multipart/form-data encoding
router.post('/photo/:id', (req, res) => {
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 = req.files.photo.data;
user.img.contentType = 'image/png';
user.save((err, obj) => {
if (err) {
throw err
}
console.log('success')
})
});
});