使用 ngx-mat-file-input 从 Angular 将文件上传为 multipart/form-data

2024-04-22

我在用着ngx-mat-file-input[0] 检索用户输入的文件,我想将其上传到服务器。端点需要一个多部分文件。我怎样才能做到这一点?

[0] https://www.npmjs.com/package/ngx-material-file-input https://www.npmjs.com/package/ngx-material-file-input


如果您正在使用<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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ngx-mat-file-input 从 Angular 将文件上传为 multipart/form-data 的相关文章

随机推荐