Tuesday 9 February 2016

File Upload With AJAX In struts 1.3 & 1.2 example

Here i have i have created one java script  function which will upload the file with ajax on struts 1.2.

this function will call Action class of struts and then it will upload the file on server directory.

JAVA Script function

function upload() {

   var photoFile= document.getElementById("promptFile").files[0];

      var formdata = new FormData();
       formdata.append("id", $("#id").val());
       formdata.append("promptFile", photoFile);

       var xhr = new XMLHttpRequest();

       xhr.open("POST", basePath + "/upload.do?method=uploadFile", true);

       xhr.send(formdata);

       xhr.onload = function(e) {

        if (this.status == 200) {
            var data=JSON.parse(xhr.responseText);
            console.log(data);
            if(data.result=="SUCCESS"){
                $("#promptFileName").val(data.fileName);
                save();
            }else
            {
                $("#promptFileName").val("");
            }
        }

       };




ActionDispatch Servlet

public class UploadAction extends ActionDispatch{

public ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
   
        PrintWriter out=response.getWriter();
     

        uploadedFileName="";
        try{
            UploadForm uploadForm=(UploadForm)form;
           
            boolean isNewUploaded=(uploadForm.getPromptFile().getFileData().length > 0 );
           
            if( !isNewUploaded)
                throw new Exception(" Failed to Upload .  Reason: File not uploaded ");
           
            File tempDir=new File(Constant.TEMP_PROMPT_FILE_DIR);
            if(!tempDir.exists())   
                FileUtils.forceMkdir(tempDir);
           
            if(isNewUploaded){
                uploadedFileName= uploadForm.getPromptFile().getFileName();
                writeFileDataToTempDir(uploadForm.getPromptFile());
            }
           
            //System Auditing
           
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("result", "SUCCESS");
            jsonObject.put("fileName", uploadedFileName);
            out=response.getWriter();
            out.println(jsonObject);
            out.flush();
           
        }catch(Exception e){
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("result", "FAILED");
           
            out=response.getWriter();
            out.println(jsonObject);
            out.flush();
        }
        finally{
            if(out != null){
                out.close();
            }
        }
        return null;
    }

   private void writeFileDataToTempDir(FormFile file) throws Exception{
        //String type="application/x-tar";
        try{
           
            if(file.getFileSize() > 0){
               
                uploadedFileName = file.getFileName();
                if(uploadedFileName != null && uploadedFileName.endsWith("mp3") || uploadedFileName.endsWith("wav"))
                {
                    byte[] fileData = file.getFileData();
                    File uploadFile=new File(Constant.TEMP_PROMPT_FILE_DIR+File.separator+uploadedFileName);
                    uploadFile.createNewFile();
                    FileUtils.writeByteArrayToFile(uploadFile,fileData);
               }else{
                   throw new Exception("Welcome file must be either mp3 or wav format");
               }
        }
        }catch(Exception exp){
        }
    }

}


UploadForm

public class HolidayForm extends ActionForm
{

    private static final long serialVersionUID = 1L;
    .....
    private FormFile promptFile;
    private String promptFileName;

    public FormFile getPromptFile() {
        return promptFile;
    }
    public void setPromptFile(FormFile promptFile) {
        this.promptFile = promptFile;
    }
       public String getPromptFileName() {
        return promptFileName;
    }
    public void setPromptFileName(String promptFileName) {
        this.promptFileName = promptFileName;
    }

}



No comments:

Post a Comment