Node.js 使用Angular、Node、Express、Multer的图像上载问题
我一直在遵循一些关于如何上传图像的指南(,对于exmaple),但是我在通过后端目录上传图像时遇到了问题。这是我的密码: 角前端Node.js 使用Angular、Node、Express、Multer的图像上载问题,node.js,angular,typescript,express,multer,Node.js,Angular,Typescript,Express,Multer,我一直在遵循一些关于如何上传图像的指南(,对于exmaple),但是我在通过后端目录上传图像时遇到了问题。这是我的密码: 角前端 //html <input type="file" name="image" (change)="onFileSelected($event)"> <button (click)="uploadImage()">Save Image</button>
//html
<input type="file" name="image" (change)="onFileSelected($event)">
<button (click)="uploadImage()">Save Image</button>
//ts
formData = new FormData();
onFileSelected(event) {
this.uploadedImage = event.target.files[0]
}
uploadImage() {
if (this.uploadedImage) {
this.formData.append('image', this.uploadedImage, this.uploadedImage.name)
console.log(this.formData.getAll('image')) //confirms file is being uploaded properly
this.httpService.upload('uploadImage/', this.formData).subscribe((message: any) => {
console.log(message)
});
}
//httpService
upload(url, file) {
console.log("uploading file")
return this.http.post(this.baseUrl + url, file);
}
HttpService完成后,我从后端收到消息“File Upload successfully”,但我的/documents/目录中没有图像。据我所知,图像应该通过req.file或req.files变量显示,但返回未定义。我做错了什么?问题在于输入字段中的角度应用程序。您的
ngModel
没有做任何事情,因为它没有正确的语法,即使如此,它也只会保存到图像的假路径
有几种方法可以从输入字段获取实际的文件对象。最简单的方法是使用onChange
事件。应该是这样的:
<input type="file" name="image" (change)="onChange($event)">
<form enctype="multipart/form-data" (ngSubmit)="uploadImage()">
<input type="file" name="image" (change)="onFileSelected($event)">
<button>Save Image</button>
</form>
您还需要更新服务中的上载方法,因为multer
解析FormData,所以您必须将数据作为FormData发送
const data = new FormData();
data.append('image', this.file, this.file.name);
return this.http.post(this.baseUrl + url, data);
注意:您正在从后端获取“文件上载成功”,因为multer即使没有要处理的数据也不会抛出错误,所以即使没有实际上载文件,您的上载端点也会始终返回成功代码201。我发现问题与FormData无法传输到后端有关,需要正确编码。根据解释,我将HTML更改为如下所示:
<input type="file" name="image" (change)="onChange($event)">
<form enctype="multipart/form-data" (ngSubmit)="uploadImage()">
<input type="file" name="image" (change)="onFileSelected($event)">
<button>Save Image</button>
</form>
保存图像
后端通过req.body收到请求,文件已成功上载。感谢您的回复。我有一些评论,因为我已经尝试过这个,但我会给它另一个机会。我将更新主帖子——我得到了相同的结果,multer没有错误,但没有文件上传。在我看来,穆特找不到“图像”对象。你知道req对象从何而来吗?Req.body,Req.file,Req.files?看起来它应该通过Req.body和Req.files来实现。但是,它需要使用类型multipart/form数据进行编码。我确实那样做了,但仍然不起作用来源:您是否正确初始化FormData?我在你更新的答案中没有看到这一部分。它只是
formData=newformdata()代码>。我也在uploadImage()函数中尝试过,但都不起作用。谢谢你的帮助,你把我推向了正确的方向。我只需要对formData进行正确编码。能否将节点代码更新为与本地计算机完全相同的代码,也许我们在后端缺少一些内容?我将继续添加index.js文件中的大部分代码。