curlie
curlie

Reputation: 295

FileUpload Multipart Springboot Error -> Required request part 'file' is not present

I am trying to upload a json file using Angular 4.0 and SpringBoot Application. I have checked and tried other solutions from Stackoverflow, but I cannot figur out what the exact problem is.

I receive the 400 BAD Request Error message with the message: Required request part 'file' is not present.

My RestController looks like this (for testing purposes), but unfortunately nothing happens.

@RestController
@RequestMapping("/api")
public class UploadRequestResource {
....

@PostMapping("/fileupload")
@Timed
public ResponseEntity<Endpoint> FileUpload(@RequestParam("file") MultipartFile file) throws URISyntaxException {
       if (file.isEmpty()) {
          System.out.println("File is empty"); }

       System.out.println("File is not empty");

       //some logic 

       return ResponseEntity.ok() ....
    }
}

I have added the following in my applicatoin configuration file:

spring:
     http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

My HTML File looks like this:

<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
    ...
   <input type="radio" [(ngModel)]="form.uploadType"  name="uploadType" value="file">&nbsp;<label for="url">File</label><br>
   <input type="file" name="file" placeholder="Upload file..." (change)="onFileChange($event)" (focus)="onFileFocus()"/>
            </div>
        </div>

The Angular ts file looks like this:

fileUpload(data): Observable<Endpoint> {
        let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post('/api/fileupload', data , options).map((res: Response) => {
            const jsonResponse = res.json();
            return this.convertItemFromServer(jsonResponse);
        });
    }

Does anyone has any idea how I should solve this error? I would be so gratful for any help. thanks

Upvotes: 1

Views: 1389

Answers (1)

curlie
curlie

Reputation: 295

So I found a solution to my problem. Instead using Content-Type: "multipart/form-data" I used Formdata (see below).

const formData = new FormData();
        formData.append('file', data, data.name);
        return this.http.post('/api/fileupload', formData).map((res: Response) => {
            const jsonResponse = res.json();
            return this.convertItemFromServer(jsonResponse);

Now it works fine.

Upvotes: 2

Related Questions