Angular 9 File upload + Spring Boot REST API

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());
}
}

One comment

  • [4202]MTM777 Casino México: Registro, Bono y Descargar APK de Slots,Únete a MTM777 Casino México, la plataforma líder en slots y apuestas online. Regístrate hoy mismo para aprovechar el mejor bono de bienvenida, descubre una increíble variedad de juegos y descarga la APK oficial para jugar desde tu móvil. ¡Vive la emoción del casino en tiempo real con MTM777! visit: mtm777

Leave a Reply