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?
-
Even though this seems kind of easy in the end I still struggeled some time with this. Hopefully I can help others with the same problem, so I posted this Q&A-style post.phip1611– phip16112019-09-17 17:25:32 +00:00Commented Sep 17, 2019 at 17:25
1 Answer
If you're using <ngx-mat-file-input> with a 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 shown down below(in this example: Java/Spring). Generally, it works with every controller, that accepts 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)