简体   繁体   中英

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. The endpoint expects a multipart-file. How can I do this?

[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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM