SPRINGMVC Ajax Upload File instance

Source: Internet
Author: User
Tags file upload

Do a file upload module, because the traditional form submission will have a page refresh, does not conform to my use requirements, so I use the Ajax submission method, here is explained, my application front end for Ajax submission, backend SPRINGMVC receive processing.

Traditional form submission File method:

<form id= "Uploadpic" action= "/user/saveheaderpic" method= "post" enctype= "Multipart/form-data" >
    <input Type= "File" name= "file"/>
    <input type= "Submit" value= "commit"/>
</form>

Using AJAX to submit a file, I have appeared the following two questions:

Ajax post (Bad Request)

HTTP Status 400-required commonsmultipartfile parameter ' pic ' is not present

Here's why the error is explained:

Question 1:

Ajax parameter error caused, upload the file Form I used the Jquery.form.js form serialization, so it is convenient to transfer the form to the background, but the binary file cannot be serialized with Form.serialize ().

So eventually I used the formdata transmission, XMLHttpRequest Level 2 added a new interface formdata. Using the Formdata object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can use the XMLHttpRequest Send () method to asynchronously submit the form. The biggest advantage of using formdata compared to normal Ajax is that we can upload a binary file asynchronously.

However, there are certain requirements for browsers using Formdata (Chrome 7+, Firefox 4+, IE + +, Opera 12+, Safari 5+), if the program needs to be compatible with the lower version of the browser, you can check other JS upload control or flash upload control.

FormData use See: Https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormData

Question 2:

This problem is caused by careless--the parameter name that is received by the backend and the name of the front-end file control are inconsistent.

OK, here's a sample of my back and forth code:

Html:

<form id= "Uploadpic" action= "#" enctype= "Multipart/form-data" >
    <input type= "file" name= "file" >
    <a href= "Javascript:savepic ()" class= "BTN Green" > Submit </a>
</form>

JS script:

<script type= "Text/javascript" >
    function Savepic () {
        var formData = new FormData ($ ("#uploadPic") [0]);  
        var ajaxurl = "${path}/rest/user/saveheaderpic";
        alert (ajaxurl);
        $ (' #uploadPic '). Serialize () could not serialize binaries, formdata upload
        //browser support required: Chrome 7+, Firefox 4+, IE + +, Opera 12+, Safari 5 +
        $.ajax ({
            type: "POST",
            //datatype: "Text",
            Url:ajaxurl,
            data:formdata,
            Async:false,  
            Cache:false,  
            contenttype:false,  
            processdata:false,
            success:function (data) {
            alert ( Data)
            ,
            error:function (data) {
                alert ("Error:" +data.responsetext);}
        });
        return false;
    }

Java back end:

/** * Avatar Image upload * @throws IOException */@RequestMapping (value = "/saveheaderpic", method = requestmethod.post) public vo ID saveheaderpic (@RequestParam ("file") commonsmultipartfile file, httpservletrequest request, HttpServletResponse
    Response) throws IOException {String resmsg = "";

        try {long starttime=system.currenttimemillis ();
        System.out.println ("FileName:" +file.getoriginalfilename ());
        String path= "/users/loukai/easylife/files/" +new Date (). GetTime () +file.getoriginalfilename ();

        System.out.println ("Path:" + path);
        File Newfile=new file (path);
        Write the file File.transferto (newFile) directly by Commonsmultipartfile method;
        Long Endtime=system.currenttimemillis ();
        System.out.println ("Run Time:" +string.valueof (endtime-starttime) + "MS");
    resmsg = "1";
        } catch (IllegalStateException e) {//TODO auto-generated catch block E.printstacktrace ();
    Resmsg = "0"; } Response.getwritER (). write (resmsg); }

Run the test and upload the file successfully.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.