I have a form with two inputs: one type text and the other is file. how can i pass the file to backend spring boot? and how to store it or get there content data with postgresql database. thank you in advance for return.
2 Answers
HTML File
<input #csvFile accept=".csv" #file (change)="onCSVFileSelect(file.files)" type="file">
TypeScript File component class
@ViewChild('csvFile') csvFile: any;
//On File Select
onCSVFileSelect(files) {
let file: File = files[0];
if (file.type == "text/csv") {
this.selectedFileName = file.name;
this.customerService.uploadCustomerFile(file).subscribe((fileUploadResponse) => {
//Success Block
}, (error) => {
//Error Block
});
} else {
//alert("Plase select .csv file");
this.reset();
}
}
TypeScript File service class
uploadCustomerFile(access_token: string, file: File): Observable<any> {
let headers = new Headers();
let options = new RequestOptions({ headers: headers });
let formData = new FormData();
formData.append('customerData', file);
return this.http.post(this.baseUrl + "getCustomerCSVFile", formData, options)
.map((res: Response) => res.json() || {});
}
Spring Controller
@RequestMapping(value = "/getCustomerCSVFile", method = RequestMethod.POST)
public ResponseGenerator getCustomerCSVFile(@RequestParam MultipartFile customerData) {
ResponseGenerator responseGenerator = new ResponseGenerator();
try {
if (customerData != null) {
System.out.println(customerData.getOriginalFilename());
}
return responseGenerator;
} catch (Exception e) {
logger.error("Error while updating user : ", e);
return responseGenerator;
}
}
Comments
You can used the ng-file-upload dependency. After adding that to your angularJs project, add this to your html file.
<div class="button btlg" ngf-select ng-model="file" name="file" ngf-min-height="100" ngf-accept="'.jar,.properties,.txt,.conf,.json'" ngf-resize="{width: 100, height: 100}">Select file</div>
<button class="bt bt-blue" type="submit" ngf-max-size="209715200" ng-click="submit()">submit</button>
Adjust ngf-accept and ngf-max-size as per your requirement. In your Js file add this
$scope.submit = function() {
$scope.uploadFile = Upload.upload({
url : '/save/file',
method : 'POST',
data : {
file: $scope.file,
fileName : $scope.fileName
},
headers : {
'Content-Type' : undefined
}
});
// Control the result
$scope.uploadFile.then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
}
Your spring boot app. In your controller.
@Autowired
@Qualifier("saveService")
SaveService saveService;
@RequestMapping(value = "/save/file", consumes = "multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public SaveFile saveFile(@RequestParam String fileName, @RequestParam MultipartFile file){
saveService.saveFile(fileName, file);
}
In your Service
@Autowired
SaveFileRepository saveFileRepository;
@Transactional(isolation = Isolation.SERIALIZABLE)
public SaveFile saveFile(String fileName, MultipartFile file) {
SaveFile saveFile = new SaveFile();
saveFile.setName(fileName);
saveFile.setId(UUID.randomUUID().toString());
try {
saveFile.setContent(file.getBytes());
} catch (IOException e) {
log.error("Error while saving content of {}", fileName);
}
saveFile = saveFileRepository.save(saveFile);
return saveFile;
}
The domain class will be
@Entity
@EntityListeners(AuditingEntityListener.class)
public class SaveFile {
@Id
private String id;
@Column
private String name;
@Lob
@Column
private byte[] content;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
The repository is just a simple repository that extends the CrudRepository
public interface SaveFileRepository extends CrudRepository<SaveFile,String>{
//Add other methods here
}
3 Comments
Aluan Haddad
This is not an AngularJS question
berrytchaks
Oh yes, my bad little did I know that there was a different between angularJs and angular. I just googled that and notice that these technologies are different. Thanks for the information.
Aluan Haddad
No problem. In fact, they are very different. AngularJS was much better in its day than Angular is now.