Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, March 6, 2014

File Uploading with Spring

In web applications that uses Spring framework some times we may need to add functionality to upload file to server. This can be done easily as follows.



First create a form to select a  file,

<!--  Form -->

<i>Uploading File With Ajax</i><br/>

<form id="form" method="post" action="/fileUpload/upload/" enctype="multipart/form-data">

  <!-- File input -->   

  <input name="file" id="file" type="file" /><br/>

</form>

<button value="Submit" onclick="uploadJqueryForm()" >Upload</button><i>Using JQuery Form Plugin</i><br/>

<div id="result"></div>

</body>

</html>
when the button clicks, it calls uploadJqueryForm() function. In that function we can submit the file to the respective controller method. Here is the uploadJqueryForm() function


function uploadJqueryForm(){
    $('#result').html('');
   $("#form").ajaxForm({
    success:function(data) { 
          $('#result').html(data);
     },
     dataType:"text"
   }).submit();
}
This fuction will submit the file and calls the path specified in the "action" tag in the above form. Then we need to write a controller method to handle that request from the function uploadJqureyForm()

@RequestMapping(value = "fileUpload/upload", method = RequestMethod.POST)
    public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response,Model model) {                 
 
      Iterator itr =  request.getFileNames();
  
      MultipartFile mpf = request.getFile(itr.next());
      System.out.println(mpf.getOriginalFilename() +" uploaded!");
      String fullFileName="";
      String filePath="";
  
      try {
                
         ufile.length = mpf.getBytes().length;
         ufile.bytes= mpf.getBytes();
         ufile.type = mpf.getContentType();
         ufile.name = mpf.getOriginalFilename();
         
         
             InputStream in= mpf.getInputStream();    
             String fileName = mpf.getOriginalFilename();            
             
             String fileExtension = fileName.substring(fileName.indexOf(".")+1,fileName.length());
                
          
           filePath="D:\\DEV\\work\\files\\Temp\\";
           fullFileName = "D:/DEV/work/files/Temp/"+fileName;
          File files = new File(filePath);
          if (!files.exists()) {
           if (files.mkdirs()) {
            System.out.println("Multiple directories are created!");
           } else {
            System.out.println("Failed to create multiple directories!");
           }
          }
          writeFile(in,fullFileName);
          
      
  
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
  
      
      return "home"; //or whatever the model you need
  
   }
In that methode we get the file as a Multipart request.

Inside this method we call writeFile() method. Here is that method.
this method will write the file into the server folder which we created in the above controller method.

private void writeFile(InputStream in,String fileName){
   
    File file = new File(fileName);
    FileOutputStream fo;
    logger.info("Saving File "+fileName);
   try {
    fo = new FileOutputStream(file);
      byte[] buf = new byte[512]; // optimize the size of buffer to your need
        int num;
        while ((num = in.read(buf)) != -1) {
         fo.write(buf, 0, num);
        }
      fo.flush(); 
        fo.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
    }

References : Reference 1Reference 2