I need to send file via POST in my web application. I have a server side in java and a client side in angular 2. I need to client send file to the server. Server's code:
@RequestMapping(method = RequestMethod.POST, value = "/run/file")
@ResponseBody
private void runImportRecordsJob(@RequestParam("file") MultipartFile file){
// Some code
}
Client's code:
Component:
export class ImportRecordsJobComponent implements OnInit {
file: File;
constructor(private jobsService: JobsService) { }
chooseFile(event: any){
this.file = event.srcElement.files[0];
console.log(this.file);
}
selectFormat(event: any){
if (event.length > 0)
this.format = event[0].key;
else
this.format = null;
}
runImportRecordsJob(){
if (confirm("Are you sure you want to run this job?")){
this.jobsService.runImportRecordsJob({file: this.file});
}
}
ngOnInit() {
}
}
Service:
@Injectable()
export class JobsService {
constructor(private http: Http) { }
runImportRecordsJob(importRecords: any){
var headers = new Headers({"Content-Type": 'application/json; multipart/form-data;'});
let options = new RequestOptions({ headers: headers });
let formData = new FormData();
formData.append("file", importRecords.file, importRecords.file.name);
this.http.post(SERVER + "/batches/run/file", formData, options).subscribe();
}
}
But I'm getting an error: nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
and formData is always empty. Can anyone suggest me a way how to send file without using ng2-uploader and stuff like that. Thanks.