【发布时间】:2022-01-05 08:52:06
【问题描述】:
需要使用 mat-form-field 上传文件并使用 web API dot net core 保存到数据库。目前我正在使用 mat-form-field 将其他数据保存到数据库。现在我正在尝试使用 mat-form-field 上传文件(图像)并需要将其发送到 Web API 控制器。有什么方法吗?
【问题讨论】:
标签: c# angular asp.net-core asp.net-web-api
需要使用 mat-form-field 上传文件并使用 web API dot net core 保存到数据库。目前我正在使用 mat-form-field 将其他数据保存到数据库。现在我正在尝试使用 mat-form-field 上传文件(图像)并需要将其发送到 Web API 控制器。有什么方法吗?
【问题讨论】:
标签: c# angular asp.net-core asp.net-web-api
//In the .html U.I You would accept the file like so
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
//Then in the .ts backend
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
这是一个示例,您可以将输入放入 Mat 字段表单中,
然后,一旦您从用户那里获得了文件,您就可以将其映射到后端,并将 http 回调到 API
【讨论】: