///我正在尝试从id为angular的节点上传多个文件,并以FormData的形式将其发送到节点服务器,但是服务器抛出了错误请求的错误。
//我试图调整我的身体解析器,但是没有用
//这是我上传图片的来源。
<div class="row">
<div class="col-md-6 offset-md-3">
<form [formGroup]="uploadImage" (ngSubmit)="onSubmitImage()" enctype="multipart/form-data">
<input formControlName="image" name="image" type="file" (change)="onImagePicked($event)" multiple/><br/>
<br>
<input type="submit" value="submit">
</form>
</div>
</div>
//这是我组件的代码
onImagePicked(e: any) {
console.log('functions')
this.fileList = e.target.files;
console.log(this.fileList);
this.uploadImage.value.image = this.fileList;
this.uploadImage.value.id = this.id;
console.log(this.uploadImage.value)
this.masterservice.onUploads(this.uploadImage.value)
.subscribe(data => {
console.log(data);
})
}
//这是用于将请求发送到节点服务器的服务的代码
onUploads(id) {
console.log(id);
const postData = new FormData();
postData.append('id', id.id)
const files: Array<File> = id.image;
console.log(files)
for (let i = 0; i < files.length; i++) {
console.log(files)
postData.append('image[]', files[i], files[i]["name"]);
}
console.log(postData.get("image[]"), postData.get('id'))
// for(var val of postData.values()){
// console.log(val)
// }
return this.http.post<any>('http://192.168.43.124:3000/api/addProjectImages', postData)
.map(res => {
return res;
});
}
//这是我的后端代码。
router.post("/api/addProjectImages", upload.array("image[]", 10), (req, res) => {
console.log(req.body, req.files);
// console.log(req.files[1], req.body.image[1]);
let data = [];
if (!req.files) {
const msg = "Please upload a valid file.";
sendData(req, res, msg, 0);
}
const url = req.protocol + "://" + req.get("host");
let image = [];
for (i = 0; i < req.files.length; i++) {
image.push(url + "/uploads/" + req.files[i].filename);
}
project.findOne({ _id: req.body.id }).then(project => {
console.log(image);
for (const img of image) {
project.images.push(img);
}
project
.save()
.then(editedProject => {
sendData(req, res, editedProject, 1);
})
.catch(err => {
sendData(req, res, err, 0);
});
});
});
我想上传文件,但是后端抛出错误的错误请求。