如果您正在使用<ngx-mat-file-input>
使用反应形式,它将返回一个带有“文件”数组的对象。该数组的元素的类型为“文件”。 File 扩展了 Blob 接口 [0][1]。 Blob 是您需要发送到服务器的内容。
第一步:您必须将表单的结果包装在FormData
-对象[2]。
<!-- Minimal form -->
<form *ngIf="fileForm" [formGroup]="fileForm">
<ngx-mat-file-input formControlName="file"></ngx-mat-file-input>
</form>
// the handler, e.g. if user presses "upload"-button
const file_form: FileInput = this.fileForm.get('file').value;
const file = file_form.files[0]; // in case user didn't selected multiple files
const formData = new FormData();
formData.append('file', file); // attach blob to formdata / preparing the request
Notice: 你可能会想到.append
将返回一个新对象,例如HttpHeaders#append
但这里的情况并非如此。FormData#append
回报void
。因此你不能这样做const formData = new FormData().append('file', file);
!
第二步:现在通过FormData
-反对HttpClient#post
.
this.http.post<void>('/upload', formData).subscribe(() => {
// worked
}, err => {
console.error(err);
});
Notice:服务器期望请求参数中的文件名为“file”,因为我们在FormData
-Object.
就是这样。
接受此文件的控制器可能如下所示(在本例中:Java/Spring)。一般来说,它适用于每个接受表单多部分请求的控制器。
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {}
[0] https://developer.mozilla.org/de/docs/Web/API/File https://developer.mozilla.org/de/docs/Web/API/File
[1] Typescript 类型信息(由您的 IDE 提供)
[2] https://developer.mozilla.org/de/docs/Web/API/FormData https://developer.mozilla.org/de/docs/Web/API/FormData