Bhanukiran Bhanukiran - 6 days ago 6
AngularJS Question

How to receive uploaded file from angularjs in grails(backend)?

I am uploading an excel file in front-end(angularjs) and want to receive it in back-end(grails resource file).I am not supposed to use GSP in my project.So how to receive the file sent via angularjs?

AngularJs code,

$scope.uploadExcelFile =function (file) {
var doc = file
var filesArr = [];
if (doc) {
filesArr.push({file: doc});
uploadCurry(filesArr);
}
}
function uploadCurry(queue){
if (arguments.length) {
this.q = queue
}
if (this.q.length) {
var curr = this.q.pop();
upload(curr.file);
}
}
function upload(file) {
if (file) {
var postdata = {
file: file,
}
roleProfileService.importExcleFile(postdata).then(function(res) {
console.log(res);
})
}
}


Angular Service file,

var importExcleFile = function(file,callback){

return $upload.upload({
url: '/api/importFile/profile',
method: 'POST',
file: file
}).progress(function(evt) {
_log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
roleProfileService.progress = 'Loading '+ evt.config.file.name +" : "+ parseInt(100.0 * evt.loaded / evt.total)+"%"
}).success(function(data, status, headers, config) {
_log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
roleProfileService.uploadsuccess = true;
if(callback) callback();


}).error(function(a,b,c,d,e){
_log("err", a,b,c,d,e);
roleProfileService.uploadfail = true;
});
}


Grails Resource file,

@Path('/api/importFile')
@Consumes(['application/json','text/plain','application/vnd.ms-excel'])
@Produces(['application/json'])

class KsaResource {
KsaService ksaService

@GET
@Path('profile')
Response getAllKsaData(MultipartFile file) {
//how to receive uploaded file here?
List<Job> jobSavedList = ksaService.importExcelData(file);
//rest of code
}
}

Answer

We can write a controller to receive the file

class ImportRoleProfileController {

    SpringSecurityService springSecurityService;

    def importUpload() {
        User currentUser = springSecurityService.getCurrentUser();
        def file = request.getFile('file')
        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
        int sheet_Num = workbook.getNumberOfSheets();
Comments