zdnmn
zdnmn

Reputation: 161

Angular 8 415 Unsupported Media Type,Content type 'application/json' not supported +Spring Boot

MY problem, I can upload files with Postman(Spring Boot).Service works, but when I do it with angular, I get an error.(15 Unsupported Media Type,Content type 'application/json' not supported)

Spring*

  @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<HttpStatus> saveProfil(@RequestParam("file") MultipartFile file) 

*******Angular *****

 const httpOptions = {
    headers: new HttpHeaders().set('Content-Type','multipart/form-data')

     }
    export class ApiService {
    
      constructor(private httpClient: HttpClient) { }
    
      postFile(path: string, body: any): Observable<any> {
        return this.httpClient.post(path, body, httpOptions).pipe(catchError(this.formatError));
    
      }
      
    }



 onSubmit(event) {

    const file = event.target.files[0];
      this.fileUpload = file;

    const formData:FormData= new FormData();
    formData.append('file',this.fileUpload);

    this.uploadService.saveProfile(formData).subscribe(res => {.....});

   

}



 saveProfile(formData: FormData): Observable<any> {
    return this.apiService.postFile(apiHost + '/Profil', formData);
  }

Upvotes: 2

Views: 3775

Answers (1)

Bellash
Bellash

Reputation: 8204

The problem is the headers you are sending. use append or the following constructor

    const headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'text/plain');

or

 const headers = new HttpHeaders({
            "Accept": "text/plain",
            'Content-Type', 'multipart/form-data'
        });

then create the post options like this

const httpOptions = {headers: headers};

Upvotes: 2

Related Questions