File Upload using the JQuery and spring



File Upload function using the JQuery

 The below function can used for the upload a file using jquery.

For large files it may show error like script execution take more time and some times its hanges.




$(document).on('change', '.uploaddocument', function() {
                var oMyForm = new FormData();
                oMyForm.append("file", this.files[0]);
                $.ajax({
                  url: 'uploaddocument.html',
                  data: oMyForm,
                  dataType: 'text',
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function(data){
                  }
                });
       });

its works fine from IE9 only. 

The above code for the jsp part. for the backend process gone through the below code.
 The example implemented using spring 3.24 version.



@RequestMapping(value = "/uploadimages", method = RequestMethod.POST)
    public ModelAndView uploadimages(MultipartHttpServletRequest request,
            HttpServletResponse response) {

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

        MultipartFile mpf = request.getFile(itr.next());

        try {
            if (mpf.getOriginalFilename() != null
                    && !"".equals(mpf.getOriginalFilename())) {
                ufile.setLength(mpf.getBytes().length);
                ufile.setBytes(mpf.getBytes());
                ufile.setType(mpf.getContentType());
                ufile.setName(mpf.getOriginalFilename());
                File file = new File(request.getSession().getServletContext()
                        .getRealPath("/") + UPLOADED_IMAGES);
                if(!file.exists()){
                    file.mkdir();
                }
                file = new File(request.getSession().getServletContext()
                        .getRealPath("/")
                        + UPLOADED_IMAGES
                        + File.separator
                        + mpf.getOriginalFilename());
                FileUtils.writeByteArrayToFile(file, mpf.getBytes());

                request.setAttribute(IMG,UPLOADED_IMAGES + "/" + mpf.getOriginalFilename());
            }
        } catch (IOException e) {

            rapidLogger.errorMessage(IO_EXCEPTION, e);

        }

        return new ModelAndView(CAPTURE_PHOTO);
    }
 

Comments

Popular posts from this blog

Drools rules decision tables implementation

Simple Captch Using javascript