File upload (with meta data) in Angular 9 & Spring Boot 2

File upload (with meta data) in Angular 6 & Spring Boot 2

In Angular side create the component and typescript file similar to this,

Part 1: Angular Side Development

Angular Template(Html) file:

[html]
<div class=”row justify-content-center”>
<label class=”ct-input-file”>My File Label Here
<input type=”file”
(change)=”onFileChange($event)”> <i
class=”icon-upload”></i>
</label>
</div>
[/html]

Note: class=”icon-upload” gives upload icon, if you don’t want then you can remove it for older way of file upload button.

Angular Component(ts) file:

  • FileUploadService is service class to deal api request and responses.
  • MetaDataBean is bean class to send to your api along with the file.

Please also read the inline comments for better understanding, feel free to post your queries if further details required.

 

[html]

// import necessary things like Component, FileUploadService and Your Bean Classes
export class FileUpload {

fileToBeUploaded: any = {};
// this is the bean you wanted to send it along with your files to your api
// this can be meta data of your file or any other form data filled along with file upload etc.
metaDataBean:MetaDataBean = new MetaDataBean();

constructor(private fileUploadService:FileUploadService) { }

// will be called once the file is selected / uploaded
onFileChange(event) {
const filesVar: FileList = event.target.files;
if (filesVar.length > 0) {
let file = filesVar[0]; // directly you can give event.target.files[0], if validation done in the template side itself
var blobData: any = new Blob([file], { type: file.type });
blobData.fileName = file.name;
this.fileToBeUploaded.file = blobData;
}
}

// to be called on click of submit
onSubmit(){
const formDataWithFileAndMetaData = new FormData();
formDataWithFileAndMetaData.append(‘file’, this.fileToBeUploaded.file, ‘File name here, if you want to send it differently’);
formDataWithFileAndMetaData.append(‘data’, JSON.stringify(this.metaDataBean));

this.fileUploadService.uploadFileWithMetaData(formDataWithFileAndMetaData).subscribe(
successResponse => {
console.log(‘Response From backend API’s ->’ + successResponse);
}, errorResponse => {
console.log(‘Error occured’+errorResponse);
}
);
}
}
[/html]

FileUploadService, service class(ts) file:

[html]
import { Injectable } from ‘@angular/core’;

@Injectable()
export class TasksService {

constructor(private http:Http) { }

uploadFileWithMetaData( formDataWithFileAndMetaData) {
return this.http.post(‘api_url_here_to_post_your_file_and_meta_data’, formDataWithFileAndMetaData);
}
}
[/html]

Till here you have successfully created file template and construted form data for both file and meta data or your custom bean and posted successfully to your backend api.

Part 2: API Development

Spring Boot Rest Controller Class:

You have to create your method with multipartfile type to get the file which is sent from the angular side in form data and use string to get the meta data as we did JSON.stringify to convert our object to string in angular side.

We have to reverse the logic here to convert the json string to our custom bean type (say MetaDataBean).

For the same purpose you can actually use jackson fasterxml jars.

[java]
@RestController
@RequestMapping(value=”/file”)
public class LmImplementationController {

@PostMapping(value=”/upload”)
public Boolean uploadFloorDiagram(@RequestParam(“file”) MultipartFile file,
@RequestParam(“data”) String stringBeanData) throws TclCommonException{

// call the string to object type method here like this,
MetaDataBean metaDataBean = (MetaDataBean) ConvertUtils.convertJsonStringToCustomObject(stringBeanData, MetaDataBean.class);
return true;
}

}
[/java]

 

 

Sample jackson fasterxml snippet to convert the string to custom bean type:

[java]
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertUtils {
// converting the json string to custom object
public static Object convertJsonStringToCustomObject(String jsonString, Class<?> classType) {
Object customObject = null;
try {
customObject = new ObjectMapper().readValue(jsonString, valueType);
} catch (Exception e) {
// handle the exceptions here
}
return customObject;
}

// converting the custom bean objects to json string
public static String convertCustomObjectToJsonString(Object object){
String jsonString = null;
try {
jsonString = new ObjectMapper().writeValueAsString(object);
} catch (Exception e) {
handle the exceptions here
}
return jsonString;
}
}
[/java]

 

 

Feel free to post your thoughts/comments/doubts/feedbacks in the below comments section.

Leave a Reply