[英]Upload File as multipart/form-data from Angular with ngx-mat-file-input
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. 我正在使用
ngx-mat-file-input
[0]从用户检索文件输入,我想将其上传到服务器。 The endpoint expects a multipart-file. 端点需要一个多部分文件。 How can I do this?
我怎样才能做到这一点?
[0] https://www.npmjs.com/package/ngx-material-file-input [0] https://www.npmjs.com/package/ngx-material-file-input
If you're using <ngx-mat-file-input>
with an reactive form it will give you back an object with a 'files' array. 如果您以反应形式使用
<ngx-mat-file-input>
,它将为您提供带有“文件”数组的对象。 The elements of this array have the type 'File'. 该数组的元素的类型为“文件”。 A File extends the Blob interface [0][1].
文件扩展了Blob接口[0] [1]。 The Blob is what you need to send to the server.
Blob是您需要发送到服务器的内容。
First step: You have to wrap the result of the form inside a FormData
-Object [2]. 第一步:您必须将表单的结果包装在
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
Notice : You might expect that .append
will return a new object like HttpHeaders#append
but that is not the case here. 注意 :您可能希望
.append
将返回一个新对象,如HttpHeaders#append
但此处并非如此。 FormData#append
returns void
. FormData#append
返回void
。 Therefore you can't do const formData = new FormData().append('file', file);
因此,您不能
const formData = new FormData().append('file', file);
! !
Second step: Now pass the FormData
-Object to HttpClient#post
. 第二步:现在将
FormData
-Object传递给HttpClient#post
。
this.http.post<void>('/upload', formData).subscribe(() => {
// worked
}, err => {
console.error(err);
});
Notice : The server expects the file in the request parameter called 'file' because we set that name in the FormData
-Object. 注意 :服务器希望在请求参数“ file”中包含该文件,因为我们在
FormData
-Object中设置了该名称。
That's it. 而已。
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. 接受此文件的控制器可能看起来像这样(在此示例中:Java / Spring),但这是所有可以接受多形式请求的服务器的通用解决方案。
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {}
[0] https://developer.mozilla.org/de/docs/Web/API/File [0] https://developer.mozilla.org/de/docs/Web/API/File
[1] Typescript Type Information (by your IDE) [1]打字稿类型信息(通过您的IDE)
[2] https://developer.mozilla.org/de/docs/Web/API/FormData [2] https://developer.mozilla.org/de/docs/Web/API/FormData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.