使用ngx-mat-file-input从Angular上载文件作为多部分/表单数据 [英] Upload File as multipart/form-data from Angular with ngx-mat-file-input
问题描述
我正在使用ngx-mat-file-input
[0]从用户检索文件输入,我想将其上传到服务器.端点需要一个多部分文件.我该怎么办?
I'm using ngx-mat-file-input
[0] to retrieve a file input from the user and I want to upload it to a server. The endpoint expects a multipart-file. How can I do this?
[0] https://www.npmjs.com/package/ngx-material-file-input
推荐答案
如果您以反应形式使用<ngx-mat-file-input>
,它将为您提供带有文件"数组的对象.该数组的元素的类型为文件".文件扩展了Blob接口[0] [1]. Blob是您需要发送到服务器的内容.
If you're using <ngx-mat-file-input>
with an reactive form it will give you back an object with a 'files' array. The elements of this array have the type 'File'. A File extends the Blob interface [0][1]. The Blob is what you need to send to the server.
第一步:您必须将表单的结果包装在FormData
-Object [2]中.
First step: You have to wrap the result of the form inside a FormData
-Object [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
通知:您可能希望.append
返回一个新的对象,如HttpHeaders#append
,但是这里不是这种情况. FormData#append
返回void
.因此,您不能执行const formData = new FormData().append('file', file);
!
Notice: You might expect that .append
will return a new object like HttpHeaders#append
but that is not the case here. FormData#append
returns void
. Therefore you can't do const formData = new FormData().append('file', file);
!
第二步:现在将FormData
-Object传递给HttpClient#post
.
Second step: Now pass the FormData
-Object to HttpClient#post
.
this.http.post<void>('/upload', formData).subscribe(() => {
// worked
}, err => {
console.error(err);
});
通知:服务器希望在请求参数"file"中包含该文件,因为我们在FormData
-Object中设置了该名称.
Notice: The server expects the file in the request parameter called 'file' because we set that name in the FormData
-Object.
就是这样.
接受此文件的控制器可能看起来像这样(在此示例中为Java/Spring),但这是所有可以接受表单多部分请求的服务器的通用解决方案.
A controller that accepts this file might look like these (in this example: Java/Spring), but this is a general solution for all servers that can accept form-multipart requests.
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {}
[0] https://developer.mozilla.org/de/docs/Web/API/文件
[1]打字稿类型信息(通过您的IDE)
[1] Typescript Type Information (by your IDE)
[2] https://developer.mozilla.org/de/docs/Web/API/FormData
这篇关于使用ngx-mat-file-input从Angular上载文件作为多部分/表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!