angular - 如何使用角度在 ts 文件中发送表单数据?
问题描述
我想使用表单数据类型将数据发送到后端。我想用html上传一张照片和名字,在上传成功的后端文件中,bur没有在前端取名字,我用postman检查了后端。这是完全有效的。
HTML 文件
<form id="myForm">
<label>Name</label>
<input type="text" id="name" name="name" >
<div>
<input name="file" id="photo" type="file" accept="image/*" (change)="selectImage($event)" />
<button type="button" (click)="upload()">Upload</button>
</div>
</form>
类型脚本文件
export class AcademicsComponent implements OnInit {
name;
images;
constructor(
private http: HttpClient,
) { }
ngOnInit() {
}
selectImage(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.images = file;
}
}
upload() {
this.name = name;
const formData = new FormData();
formData.append('profileImage', this.images)
formData.append('name', this.name)
const url = "http://localhost:3000/academics/uploadfile";
this.http.post(url,formData).subscribe(res => {
console.log(res)
});
}
}
后端响应
{ fieldname: 'profileImage',
originalname: '19682.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'uploads/',
filename: '19682.png',
path: 'uploads\\19682.png',
size: 1111883 }
{ _id: 5da03efb74492c3f8891c93f,
path: '/uploadfile/19682.png',
name: '',
__v: 0 }
解决方案
您没有将输入中的名称值绑定到任何东西。
例如,您可以为此使用两种方式的数据绑定。
<form id="myForm">
<label>Name</label>
<input type="text" id="name" name="name" [(ngModel)]="name">
<div>
<input name="file" id="photo" type="file" accept="image/*" (change)="selectImage($event)" />
<button type="button" (click)="upload()">Upload</button>
</div>
</form>
然后像这样上传
upload() {
const formData = new FormData();
formData.append('profileImage', this.images)
formData.append('name', this.name)
const url = "http://localhost:3000/academics/uploadfile";
this.http.post(url,formData).subscribe(res => {
console.log(res)
});
}
推荐阅读
- android - Android - 如何在点击时更改包含标签内的布局?
- selenium - 此 Selenium 命令的正确语法
- docker - 你可以通过 Terraform 在 GCP 中运行 Docker 容器吗?
- sql - 为什么在 AS3 中尝试获取数组的长度属性失败?
- python - 根据另一个查询集的结果过滤查询集
- highcharts - 增加和修复点highcharts
- networking - 源与目标端口
- python-3.x - Jupyter Notebook 中的 Python 3.x folium TraceBack 错误
- ios - 金属着色器中采样器 lod_options (MSL) 的正确用法是什么?
- php - 这种数字格式有什么问题?