2

Which is the best or easiest ways to upload file over Ajax in Spring 3.0?
I want to submit a form over Ajax which will contain a File.Also solution should not be dependant on Flash etc. like Uploadify. I tried Jquery form plugin but not able to make it work.You can check my previous question for more details.

Thanks!


EDIT : I want to submit form over Ajax which will contain a file. On server side I want to collect it in a model attribute.

Community
  • 1
  • 1
Ajinkya
  • 22,324
  • 33
  • 110
  • 161

3 Answers3

0

I recently did this using Dojo Iframes. Here's the code for that (need to call it from action="return submitForm();" from the form tag):

submitForm = function() {
dojo.io.iframe.send({
    url : "/uploadForm",
    form : "html_form_id",
    method : "POST",
    handleAs : 'text',
    load : function(response, ioArgs) {
            //handle your response here...
            return response;
    },
    error : function(response, ioArgs) {
        if (ioArgs.xhr.status != 0) {
            try {
                //handle error here
            } catch (e5) {
            }
        }
        return response;
    }
});
return false;
}

On the server side, in your Spring Controller, you would handle this as:

    @RequestMapping(method = RequestMethod.POST, value = "/uploadForm")
    public ModelAndView onSubmit(
            @RequestParam("file") MultipartFile multipartFile,
        final HttpServletResponse response)
        throws Exception 
    { 

        String fileName="";
        if(multipartFile!=null)
        {
                    fileName = multipartFile.getOriginalFilename();
        }

        //file inputstream can be accessed as multipartFile.getInputStream()

        String resultCode = "0";

        final String responseHTML = "<html><head></head><body><textarea>" + resultCode + "</textarea></body></html>";
        response.setContentType("text/html");

        final OutputStream responseStream = response.getOutputStream();
        responseStream.write(responseHTML.getBytes());
        responseStream.write("\r\n".getBytes());
        responseStream.close();
    }

You'll need to name your file type input parameter as "file" (as the handling functions says @RequestParam("file"))

rogermenezes
  • 1,143
  • 8
  • 12
0

Used Ajax upload it worked. But it calls the controller as soon as file is selected.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
0

have you tried malsup jquery form plugin.... it worked fine for me

http://malsup.com/jquery/form/
pawan
  • 401
  • 1
  • 5
  • 14