Upload File as multipart/form-data from Angular with ngx-mat-file-input

匆匆过客 提交于 2020-02-02 14:46:48

问题


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


回答1:


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.

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

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);!

Second step: Now pass the FormData-Object to 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.

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.

@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {}

[0] https://developer.mozilla.org/de/docs/Web/API/File

[1] Typescript Type Information (by your IDE)

[2] https://developer.mozilla.org/de/docs/Web/API/FormData



来源:https://stackoverflow.com/questions/57979241/upload-file-as-multipart-form-data-from-angular-with-ngx-mat-file-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!