Thursday, October 27, 2016

Upload a file on Spring MVC server with Cordova File Transfer Plugin

Write a angularjs service using cordova file transfer plugin. Need to mention   ContentType header value undefined. Browser will do rest of the work for us.
 (function(){
    "use strict";
   
    angular
        .module("demoApp")
        .service("fileTransferService", ["dataSharingService", 
               fileTransferService]);
   
    function fileTransferService(dataSharingService){

        return {
            uploadFile : function(fileURL, uploadURL, uploadConfig, 
                     successCB, errorCB, progressCB) {
                var options = new FileUploadOptions();
                options.fileKey = uploadConfig.fileKey;
                options.fileName = uploadConfig.fileName;
                options.mimeType = uploadConfig.mimeType;
                options.headers = {
                    "X-Auth-Token" : dataSharingService.getAuthToken(),
                    "Content-Type" : undefined
                }
               
                if(uploadConfig.params) {
                    options.params = uploadConfig.params;
                }

                var ft = new FileTransfer();
                if(progressCB) {
                    ft.onprogress = progressCB;
                }
                ft.upload(fileURL, encodeURI(uploadURL), successCB,
                       errorCB, options);
            }
        };
    }
   
  })();
 
 

Spring MVC controller method

     @RequestMapping(value = "/attachment", method = RequestMethod.POST,
   produces = {"application/json"})
 public Map uploadAttachment(
   @RequestHeader(value = Constants.AUTH_HEADER_NAME,
                        required = true) String authToken,
   HttpServletRequest request,
   @RequestParam(required = true) int requestId)
                        throws FileUploadException {
  logger.info("Uploading file");
  
  ServletFileUpload fileUpload = 
                         new ServletFileUpload(new DiskFileItemFactory());
  List fileItems = fileUpload.parseRequest(request);
  
  System.out.println("===========================");
  System.out.println("file name:" + fileItems.get(0).getName()
                             + " getOriginalFilename:" 
    + " size:" 
    + fileItems.get(0).getSize());
  System.out.println("===========================");
  
  HashMap response = new HashMap<>();
  response.put("success", true);
  return response;
 }