Wednesday 1 October 2014

Struts2 File upload using Ajax & Jquery uploadify

Struts2 File upload  using Ajax & Jquery uploadify

         The Struts2 framework provides built-in support for file uploads using "Form-based File Upload". When a file is uploaded it will be stored in a temporary directory and they should be moved by your Action class to a permanent place or directory to ensure the file is not lost.

   You can download jquery.uploadify.min.js file from uploadify.org, include both js and css files to your form

         File uploading in Struts is possible through a pre-defined interceptor called FileUpload interceptor which is available (org.apache.struts2.interceptor.FileUploadInterceptor ).

Add below code snippet to your Jsp file(Multiple is optional):

<script src="js/jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/uploadify.css" />

 ....
<form ....action="uploadfiles.do">
 <input id="file_upload" name="myFile" type="file" multiple="multiple" />
 <div id="queue"></div>

.....
</form>

<script type="text/javascript">
    $('#file_upload').uploadify({
        'formData': {hoardingid: $("#hoardingid").val()},
        'swf'     : 'js/uploadify.swf',
        'uploader': 'hrdimgs.do',
        buttonText:'Add Photos',
        buttonClass:'uploadimg',
        height:22,
        width:100,
        fileSizeLimit:"2MB",
        fileTypeDesc:'Images',
        fileTypeExts:'*.gif;*.png;*.jpg',
        removeCompleted:false,
        fileObjName:'myFile'
    });

</script>

Add the following code in struts.xml file:

    <action name="uploadfiles" class="com.struts2.uploadFileAction">
       <interceptor-ref name="basicStack">
       <interceptor-ref name="fileUpload">
           <param name="allowedTypes">image/jpeg,image/gif</param>
       </interceptor-ref>      
   </action>
 
 
Now we are ready to implement you action class, Add the following code in your action to save the file in destPath before its loss:
   Properties in your action with setter and getter methods:

    private File myFile;
    private String myFileContentType;
    private String myFileFileName;
    private String destPath = Constants.IMGSAVEPATH;

.................

Method need to write, Here you can not use same session from normal action and uploadify.swf , so you need to put the saved file path in your servlet context or you should save in your database immediately.

public String uploadImages(){
        try {           
              File destFile  = new File(destPath, myFileFileName);
             FileUtils.copyFile(myFile, destFile);
             //putting files in context, to use after submit the form.

             HttpServletRequest request = ServletActionContext.getRequest();
             List<File> files = (List<File>)request.getServletContext().getAttribute("uploadedfiles");
             if(files == null){
                 files = new ArrayList<File>();               
                 request.getServletContext().setAttribute("uploadedfiles", files);
             }
             files.add(destFile);
        } catch (Exception e) {
            e.printStackTrace();
              return ERROR;
        }
        return ActionSupport.NONE;
    }


Your done  Thats it!

No comments:

Post a Comment