Combined with SPRINGMVC, use Ajax upload base64 picture data _ Upload File

Source: Internet
Author: User
Tags base64 getmessage

Note (other applications): Use the canvas canvas for the DOM elements required in HTML, draw, use Todataurl to convert to Base64 encoding upload picture


First, front-end:

<input type= "File" id= "MyImage" name= "MyImage"/>  
1 1
<script type= "Text/javascript" > $ ("#myImage"). Bind (' Change ', function () {UploadFile ($ (this));

    });

        Directly obtain base64 data by onchange Q function uploadfile (file) {var f = file.files[0];

        var reader = new FileReader ();
            Reader.onload = function () {var data = E.target.result; if (Data.lastindexof (' data:base64 ')!=-1) {data = Data.replace (' data:base64 ', ' data:image/jpeg;base64 ')
            ); 
            else if (Data.lastindexof (' Data:, ')!=-1) {data = Data.replace (' Data:, ', ' data:image/jpeg;base64, ');
            } if (iscanvassupported ()) {}else{alert ("Your browser does not support");

        }

        };
        Reader.onerror = function () {Console.log ("Upload failed");
    } reader.readasdataurl (f); //ajax Asynchronous Upload function Ajaxuploadbase64file (base64data) {var url = window.location.protocol + '//' + Windo W.location.host + "/reGister/uploadbase64 "; $.ajax ({url:url, type: "Post", Data:{base64data:base64data}, DataType: "Jso 
                N ", success:function (data) {if (data.success = = True) {Console.log (" upload succeeded ");
                }else{console.log ("Upload failed");
            }, Error:function () {Console.log ("Upload failed");
    }
        }); 


    };
        Whether to support canvas function iscanvassupported () {var elem = document.createelement (' canvas '); Return!!
    (Elem.getcontext && elem.getcontext (' 2d '));

};   </script>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 1 2 3 4 5 6 7-8--9 10---11 12--13 14 15 16 17 18 19-20 21 22 23 5 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60-61

Second, backstage:

    @RequestMapping (value= "/uploadbase64", Method=requestmethod.post) @ResponseBody public actionresult<map<s Tring,string>> base64upload (@RequestParam String base64data, httpservletrequest request, HttpServletResponse Response) {actionresult<map<string,string>> result = new Actionresult<map<string,string>&gt
        ;();
            try{logger.debug ("Upload file data:" +base64data);
            String Dataprix = "";

            String data = "";
            Logger.debug ("To judge the data"); if (Base64data = null | |
            "". Equals (Base64data)) {throw new Exception ("Upload failed, upload picture data is empty");
                }else{String [] D = base64data.split ("base64,");
                    if (d!= null && d.length = = 2) {Dataprix = d[0];
                data = d[1];
                }else{throw new Exception ("Upload failed, data not valid"); } logger.debug ("Parsing the data, getting the file name andStream data ");
            String suffix = ""; if ("DATA:IMAGE/JPEG;").
            Equalsignorecase (Dataprix)) {//DATA:IMAGE/JPEG;BASE64,BASE64 encoded JPEG picture data suffix = ". jpg"; else if ("Data:image/x-icon;").
            Equalsignorecase (Dataprix)) {//DATA:IMAGE/X-ICON;BASE64,BASE64 encoded icon image data suffix = ". ico"; else if ("data:image/gif;").
            Equalsignorecase (Dataprix)) {//DATA:IMAGE/GIF;BASE64,BASE64 encoded GIF image data suffix = ". gif"; else if ("data:image/png;").
            Equalsignorecase (Dataprix)) {//DATA:IMAGE/PNG;BASE64,BASE64 encoded PNG picture data suffix = ". png";
            }else{throw new Exception ("Upload image format is not valid");
            String tempfilename = getrandomfilename () + suffix;

            Logger.debug ("Generate File name:" +tempfilename);
            Because of the Base64decoder jar problem, use the toolkit provided by the Spring framework byte[] bs = base64utils.decodefromstring (data); try{//Using Apache-provided tool class operation Flow FileutilS.writebytearraytofile (New File (Global.getconfig (upload_file_paht), TempFileName), BS);
            }catch (Exception ee) {throw new Exception ("Upload failed, write file failed," +ee.getmessage ());   
            } map<string,string> Map =new hashmap<string,string> ();
            Map.put ("TempFileName", tempfilename);
            Result.setresultmessage ("Upload success");
            Result.setdata (map);
        Logger.debug ("Upload success");
            }catch (Exception e) {logger.debug ("Upload failed," +e.getmessage ());
            Result.setsuccess (FALSE);  
        Result.setresultmessage ("Upload failed," +e.getmessage ());
    return result; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 1 2 3 4 5 6 7 8 9 10 11 12-13--14 15---16 17--18 19 20 21 22 23 24-25 26 27 28 0 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57-58

Reference:
BASE64 encoding and Image interchange,
JAVA to convert base64 image data to local pictures,
How to convert a picture into a base64 in the background into a picture placed locally

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.