I am trying to upload a csv file using Angular 4.
This is my controller in spring boot -
@PostMapping("/sop-master/csv-upload")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<SopMasterDto> uploadCSV(@RequestParam("file") MultipartFile file, @RequestBody SopMasterDto sopMasterDto) throws IllegalStateException, IOException {
return convertToDtos(sopMasterService.updateSopMaster(file, sopMasterDto.getUsername(),sopMasterDto.getPassword()), SopMasterDto.class);
}
And this is how I send my csv file in http post using Angular 4 -
uploadCSV(file: File) {
let formData:FormData = new FormData();
formData.append('file', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data; boundary=Inflow');
headers.set('Accept', 'application/json');
let options = new RequestOptions({ 'headers': headers })
return this.http.post(AppSettings.API_ENDPOINT + 'manage/sop-master/csv-upload/', formData, options)
.map((res) => console.log(res))
.catch(error => Observable.throw(error));
}
This is what I have in my view -
<input type="file" class="btn btn-default" accept=".csv" (change)="changeListener($event.target.files)">
changeListener (files: FileList) {
if (files && files.length > 0) {
let file: File = files.item(0);
this.manageService.uploadCSV(file)
.subscribe((response) => {
this.refreshDatatable();
});
}
}
So file upload works absolutely fine when done through Postman but I keep getting this error when done through Angular 4 -
"status":400, "error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException", "message":"Required request part 'file' is not present"
Update:
Attaching a screenshot of the error that appears on my browser console.
Request Headers
Request Header after removing custom boundary from request
Request Headers after removing content type from headers