In Angular Component
Construct the formData with all the required fields including your file and the different inputs you need to pass along with your file.
constructFormData(){ let formData = new FormData(); formData.append('couponCode', this.couponCode); formData.append('file',this.networkFileUploaded); // add more inputs as you need this.submitRequest(formData); }
on file upload assigning the uploaded to files to networkFile variable, the same only sent to the backend in the formData
onFileUpload(event: any) { const target: DataTransfer = (evt.target) as DataTransfer; if (target.files[0]) { this.filename = target.files[0].name; this.networkFile = target.files[0]; this.constructFormData(); } }
submitRequest(formData:FormData){ this.couponService.submitFileAndData(formData).subscribe((success)=>{ console.log("response received is "+success); }, (error)=>{ console.log("Exception while hitting the file upload service "+error); }); }
In Angular Service
submitFileAndData(formData:FormData) { let url = "http://localhost/coupons/upload"; return this.httpClient.post<any>(url, formData); }
In Spring Boot Rest API Controller
@RequestMapping(path="/upload", method=RequestMethod.POST, consumes = {"multipart/form-data"}) public boolean uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("couponCode") String couponCd){ try{ System.out.println("uploaded file is "+file); System.out.println("passed coupon code is "+couponCd); }catch(Exception e){ logger.error("Exception while upload "+e.getMessage()); } }