I am trying to upload file from Angular version (13.3.8) , Primeng (13.2.1) to Spring Boot as Multipart File, But i am not able to get the file in the post method (status: 415, error: 'Unsupported Media Type')
File Upload Component
<p-card header="Import file">
<p-fileUpload
customUpload="true"
(uploadHandler)="onUpload($event)"
[multiple]="false"
accept=".stk">
</p-fileUpload>
</p-card>
Component.ts
onUpload(event):any {
if (event.files.length === 0) {
return;
}
const file = event.files[0];
this.service.importFile(file).subscribe(
(response) => {
// Handle success response
console.log(response);
},
(error) => {
// Handle error response
console.error(error);
}
);
}
Service
importFile(file: File) : Observable<any>{
const formData: FormData = new FormData();
formData.append('file', file, file.name);
const headers = new HttpHeaders();
//this is the important step. You need to set content type as null
headers.set('Content-Type', null);
headers.set('Accept', "multipart/form-data");
headers.set('encType', "multipart/form-data");
let params = new HttpParams();
return this.http.post(baseUrl+"/uploadFile", formData, { headers ,params});
}
Spring boot
@PostMapping(value = "/importStackup", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<String> importStackSet(@RequestParam("file") MultipartFile multiPart) {
//code
}
Error :
[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]
Using the request
method instead of the post
one could help.
If you take a look at the HttpClient
jsdoc here is what you can find:
/**
* Constructs a request that interprets the body as a `Blob` and returns
* the full event stream.
*
* @param method The HTTP method.
* @param url The endpoint URL.
* @param options The HTTP options to send with the request.
*
* @return An `Observable` of all `HttpEvent`s for the request,
* with the response body of type `Blob`.
*/
So in your case that would give something like that:
importFile(file: File) : Observable<HttpEvent<Blob>> {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
const request = new HttpRequest('POST', `${baseUrl}/uploadFile`, formData);
return this.http.request(request);
}