Reputation: 215
How to send multiple files using angular.
One file working fine as below without any issue. used multipart
file.
let formdata = new FormData();
formdata.append("file", file);
formdata.append("param", obj);
This will go as binary in request.
How can I send multiple files together? if I used list that will go like this - [object File][object File]
and back end cannot resolve
back end server.
@RequestParam(name = "param", required = true) String param,
@RequestParam(name = "file", required = false) MultipartFile[] file
Upvotes: 0
Views: 596
Reputation: 941
You can create a common function which can be used for single and multiple image upload and as well you can use it in multiple modules as well
it will be as follows
step 1 : create common functions in your shared service as follows
/**
* @description: this function will set the image in form data in returns it in the response
* @param e : file object
* @param extention : allowed extentions which allow to upload
* @param multiple : single or multiple
*/
uploadImage(e, extention = ['png', 'jpeg', 'jpg'], multiple = "") {
let fileLength = e.target.files.length;
let response: any = {};
response.images = [];
let uploadFile: any;
if (fileLength > 1 || multiple != "") {
for (let eachFile of e.target.files) {
let returnImage = this.setImageInResponse(eachFile, extention);
if (!returnImage.ImageError) {
response.images.push(returnImage);
} else {
response.ImageError = returnImage.ImageError;
}
}
} else {
uploadFile = e.target ? e.target.files[0] : null;
if (uploadFile) {
response = this.setImageInResponse(uploadFile, extention);
}
}
return response;
}
/**
* @desc: this function will set individual file object in from data
* @param uploadFile : object of single file
* @param extention : allowed extentsions
*/
setImageInResponse(uploadFile, extention) {
let response: any = {};
let tmpExtension = extention;
let tmpFileExtension = uploadFile.name.split('.').pop().toLowerCase();
if (tmpExtension.indexOf(tmpFileExtension) > -1) {
response.uploadFile = uploadFile;
var reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
response.uploadImgUrl = reader.result;
}
reader.readAsDataURL(uploadFile);
}
else {
let errorString = tmpExtension.toString();
response.ImageError = "You can upload only " + errorString;
}
return response;
}
step 2 : call upload Image function with required parameters
so you will receive the whole formdata of single or multiple which you want to get in your module
and then do your next step
Upvotes: 1