file - 在同一个请求中发送 Reactive Form 和图片
问题描述
我有一些字段的反应形式:
this.pointForm = new FormGroup({
X_WGS84: new FormControl(null, Validators.required),
Y_WGS84: new FormControl(null, Validators.required),
country: new FormControl(null),
state: new FormControl(null),
... etc
在 onSubmit 方法中,我将表单中的字段分配给 Point 类:
export class Point {
X_WGS84: number;
Y_WGS84: number;
country?: string;
state?: string;
... etc
但我不知道,如何在同一个请求中发送表单数据和图像。
onSubmit() {
if (this.pointForm.valid) {
Object.keys(this.pointForm.value).forEach(key => {
this.point[key] = this.pointForm.value[key] === '' ? null : this.pointForm.value[key];
});
this.httpService.addPoint(this.point, this.fileToUpload).subscribe(
point => {
this.router.navigate(['/home']);
},
error => {
console.log(error.statusText);
});
}
}
我做了这样的事情:
constructor(private http: HttpClient) {}
addPoint(point: Point, fileToUpload: File): Observable<Point> {
const formData: FormData = new FormData();
formData.append('image', fileToUpload, fileToUpload.name);
formData.append('Point', point);
return this.http.post<Point>('http://localhost:8000/point/new', formData);
}
但:
- 我不认为我应该这样做
- 我认为,如果出现我不明白的错误:
发送此类请求的正确方法是什么?
解决方案
我用来发送此请求的函数 append(),需要 Blob 或字符串类型。我发送对象,所以我应该将其更改为 JSON 字符串。现在它可以正常工作了。
addPoint(point: Point, fileToUpload: File): Observable<Point> {
const formData: FormData = new FormData();
formData.append('image', fileToUpload, fileToUpload.name);
formData.append('Point', JSON.stringify(point));
return this.http.post<Point>('http://localhost:8000/point/new', formData);
}
推荐阅读
- javascript - 读取图像的功能 - reactjs
- node.js - 为什么formdata返回一个空对象?
- julia - Julia - 线性并行化
- r - TIdyverse 使用列中的值进行变异以引用可能不同行中的另一个列值
- reactjs - 访问获取
从原产地 已被空闲 chrome 会话的 CORS 策略阻止 - pandas - 我想画一个最大值的饼图
- c - bits/X(例如 bits/errno.h)头文件从何而来?
- php - 将多个数据值添加到 ajax 数据字符串
- javascript - 如何访问在脚本中创建的元素?
- node.js - “npm run build --prod”中的 --prod 标志是什么?