Navyah
Navyah

Reputation: 1680

Upload a file using Ajax Request to Spring MVC Controller

I want to upload a file from jsp page to controller using Ajax request, I am not sure where I went wrong but my code is not sending request to the controller.

Jsp:

  function FileUploadRequest()
        {
            var fd = new FormData();
            fd.append("FileUpload", document.getElementById('FileUpload').files[0]);

             alert(fd);
             $.ajax({  
                    type :"Get",   
                    url : "fileUploadInfo.html",   
                   data:fd,
                    //data:fd ? fd : form.serialize(),

                    success : function(response) {  
                    alert(response); 
                   //document.getElementById("FileUploadForm").reset();
                  }   
                 });
        }
        </script>
    <form id="FileUploadForm"  enctype="multipart/form-data">
      <table width="100%" border="0" cellspacing="5" cellpadding="0">
       <tr>
                <td align="left" valign="middle">Config File</td>
                <td align="left" valign="middle"><input type="file" id="FileUpload"></td>
              </tr>
              <tr>
        <td align="left" valign="middle">&nbsp;
        </td>
        <td align="left" valign="middle">
        <input type="reset" name="button" id="button" value="Clear">&nbsp;
        <input type="button" name="button" id="button" value="Submit" onclick="FileUploadValidation();"></td>
      </tr>
      </table>
      </form>

Controller:

@RequestMapping(value ="/fileUploadInfo", method = RequestMethod.GET)

        public @ResponseBody String HelloWorld(MultipartHttpServletRequest request,
                HttpServletResponse response)
        {

             Iterator<String> itr =  request.getFileNames();

             MultipartFile mpf = request.getFile(itr.next());
             System.out.println(mpf.getOriginalFilename() +" uploaded!");
            return "Hi";


        }

Upvotes: 0

Views: 1093

Answers (1)

Ramzan Zafar
Ramzan Zafar

Reputation: 1600

You can do it like this have a fucntion like below and use ajaxForm

function ajaxUploading() {

    $("#FileUploadForm").ajaxForm({
        beforeSend: function () {
            var percentVal = '0%';

        },
        resetForm: true,
        uploadProgress: function (event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
        },
        beforeSerialize: function ($Form, options) {

           //Do anything
        },
        success: function (data, status, xhr, $form) {
             //Do anything
        }
});


}

Then on server Side

@RequestMapping(value = "fileUploadInfo", method ={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file,
            HttpServletRequest request, HttpServletResponse response,
            ) throws IOException {


        String fileName = null;


        if (null != file && !file.isEmpty()) {
            fileName = file.getOriginalFilename();



            String path = "Can be any path on disk";

            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            Utils.uploadFile(file, path, fileName);
    }
}

Implementation of UploadFile Util Function:

public static boolean uploadFile(MultipartFile file, String path,
            String fileName) {
        boolean uploaded = false;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = file.getInputStream();
            outputStream = new FileOutputStream(path + "/" + fileName);

            int readBytes = 0;
            byte[] buffer = new byte[100];

            while ((readBytes = inputStream.read(buffer, 0, 100)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
            uploaded = true;
        } catch (Exception e) {
            e.printStackTrace();
            uploaded = false;
        }
        return uploaded;
    }

Upvotes: 1

Related Questions