HTML5 Ajax Java Interface upload image

Source: Internet
Author: User

HTML5 image upload "File Upload"
On the internet to find a lot of information, mainly on 2 kinds of

How 1.from forms are submitted

<form action= "Pushusericon" method= "post" enctype= "Multipart/form-data" >      <table>          <tr>              <td width= "align=left>" picture:</td>              <td><input type= "file" name= "file"/></td >                     </tr>          <tr>              <td width= "align=" "Left" > User id:</td>              <td>< Input type= "text" name= "userId"/></td>                     </tr>         <tr>            <td><input type= " Submit "> </td>         </tr>    </table>  

Note: enctype= "Multipart/form-data" must be filled

1.1.Java page Submit directly:

    @RequestMapping (value= "/pushusericon", Method=requestmethod.post)  @ResponseBody public String Pushusericon ( HttpServletRequest request, HttpServletResponse response) throws Ioexception,baseexception {    String result = null; String userId = Request.getparameter ("UserId"); try{//transition to Multiparthttprequest (where the focus is)       multiparthttpservletrequest multipartrequest  =  ( multiparthttpservletrequest) request;       Get the 1th picture (files uploaded according to the name of the foreground)        multipartfile file  =  multipartrequest.getfile ("file");     result = Uploadimageservic.uploadfile (file, request, userId);        SYSTEM.OUT.PRINTLN ("Result:" + result);       Response.setcontenttype ("Text/html;charset=utf8");       Response.getwriter (). Write ("Result:" + result);    } catch (Exception e) {baseexception baseexception = new Baseexception (e); Baseexception.seterrormsg ("Upload API Exception "); Throw baseexception; }          return  null;        

  

1.2. There are a lot of native JS and jquery online, there is not much to say.
1.2.1. Fromdata two ways to create

var formData = new FormData ($ ("#myForm") [0]);//Use form form to construct FormData object directly; You do not need the following Append method to assign a value to the form.                       //var formData = new FormData ();//Constructs an empty object, and assigns a value using the Append method below.  //       formdata.append ("policy", "");       formdata.append ("signature", "" ");  //       

2. Do not submit from the From form:

<table style= "border:1px solid black; width:100% ">     <tr>            <td width=" align=left> pictures:</td> <td><input type=              " File "  id=" imagefile "Name=" img "multiple=" multiple "/></td>            <td>                <input type=" Button "value=" calls "onclick=" pushimg () "/>            </td>        </tr>        </table>

HTML on these, I think everyone should be able to understand, the following is to say the 2 ways of submission, how AJAX code? "From form submission method can also use JS or directly submit page refresh"

There are also 2 types of Ajax encodings:
1. Native JS

function sub () {var file = document.getElementById ("ImageFile");    var files = file.files;    for (var i = 0; i < files.length;i++) {UploadFile (files[i]);   }}var xhr = null;function uploadfile (file) {xhr = new XMLHttpRequest ();    /* Xhr.addeventlistener ("error", uploadfailed, false); Xhr.addeventlistener ("Abort", uploadcanceled, false); */Xhr.open ("Post", "upload/", true); Access controller is upload, after must add '/' otherwise will error "Org.apache.catalina.connector.RequestFacade cannot be cast to    Org.springframework.web.multipart.Mult ... ", but if it's a multi-level URL" such as xx/xxx/00/upload/0 "It's okay.    var fd = new FormData ();    Fd.append ("UserID", "1");    Fd.append ("Errdevicetype", "001");    Fd.append ("Errdeviceid", "11761B4A-57BF-11E5-AEE9-005056AD65AF");    Fd.append ("Errtype", "001");    Fd.append ("Errcontent", "XXXXXX");    Fd.append ("Errpic", file);    Xhr.send (FD); Xhr.onreadystatechange = CB;}        Function CB () {if (Xhr.status = =) {var b = xhr.responsetext; if (b = = "Success") {           Alert ("Upload successful!        "); }else{alert ("Upload failed!        "); }    }}

2.jquery

function pushimg (obj) {debugger; var url = "upload/"; Access controller is upload, after must add '/' otherwise will error "Org.apache.catalina.connector.RequestFacade cannot be cast to    Org.springframework.web.multipart.Mult ... ", but if it's a multi-level URL" such as xx/xxx/00/upload/0 "It's okay.    var param = $ ("#errorParameter"). Val (); var files = $ ("#imageFile"). Get (0). Files[0];    Gets the contents of the file control var fd = new FormData ();    Fd.append ("UserID", "1");    Fd.append ("Errdevicetype", "001");    Fd.append ("Errdeviceid", "11761B4A-57BF-11E5-AEE9-005056AD65AF");    Fd.append ("Errtype", "001");    Fd.append ("Errcontent", "XXXXXX");    Fd.append ("Errpic", files); $.ajax ({type: "POST", contenttype:false,//must be false to avoid jquery's default handling of Formdata, XMLHttpRequest Formdata Correct handling of processdata:false,//must be false to automatically add the correct Content-type url:url, DATA:FD, success:funct            Ion (msg) {debugger;            var jsonstring = json.stringify (msg); $ ("#txtTd"). Text (jsonstring) alert (JsonstriNG);            }, Error:function (msg) {debugger;        Alert ("Error");  }    });}

Now the front-end should be almost, now is the interface, my parameters and access to the path are good, now the interface service:
Spring MVC framework:

@RequestMapping (value = {"Upload"}) public void Pusherrordata (HttpServletRequest request,httpservletresponse response ) throws Baseexception {String userid=request.getparameter ("UserID");//transition to Multiparthttprequest (where the focus is) This is the above Ajax mentioned if the direct access to this interface without adding "/", this transformation will be an error multiparthttpservletrequest Multipartrequest = (multiparthttpservletrequest) Request;//multipartfile file = Multipartrequest.getfiles ("Errpic");//Gets the collection of files corresponding to the jquery $ ("#imageFile"). Get (0). files// Get the 1th picture (files uploaded according to the name of the foreground) multipartfile file = Multipartrequest.getfile ("Errpic"); Corresponds to jquery $ ("#imageFile"). Get (0). files[index]map<string, object> Map = new hashmap<string, object> (); if ( Null!=file &&!file.isempty ()) {try {map = common.uploadfile (file)} catch (IOException e) {baseexception baseexc Eption = new Baseexception (e);//baseexception.seterrormsg (imgerrormsg); throw baseexception;}}} /** * Image Upload * * @param file * @return * @throws ioexception * @throws baseexception */public static map<string, object& Gt Wp.Oadfile (multipartfile file) throws IOException, baseexception {String fail = configbundlehelper.getvalue ("Busconfig", " Fail ");//upload Failed status String success = Configbundlehelper.getvalue (" Busconfig "," success ");//Upload success status String errormsg = Configbundlehelper.getvalue ("Busconfig", "imgerrormsg");//Upload error message string FilePath = Configbundlehelper.getvalue (" Busconfig "," FilePath ");//The upload path, originally a relative path, but after the release path will be created in the Tomcat bin directory, so the interface upload path is a challenge, I use absolute path, wait to publish to the Linux environment, Modifying the path to a resource address in Linux through a configuration file "Prevent project deletion while resource files are not lost" and then re-publish the project with the Linux command to import the resource files we need into our published project. String size = Configbundlehelper.getvalue ("Busconfig", "fileSize"); String Interfaceservice = Configbundlehelper.getvalue ("Busconfig", "Interfaceservice"); Long maxfilesize = ( integer.valueof (size)) * 1024 * 1024; String suffix = file.getoriginalfilename (). substring (File.getoriginalfilename (). LastIndexOf (".")); Long fileSize = File.getsize (); map<string, object> map = new hashmap<string, object> (); if (Suffix.equals (". png") | | suffix.equals (". jpg")) {if (fileSize &LT MaxFileSize) {//System.out.println ("FileSize" +filesize); string filename = File.getoriginalfilename (); filename = new String (filename.getbytes ("iso-8859-1"), "UTF-8"); File Tempfile = new file (FilePath, New Date (). GetTime () + fileName), try {if (!tempfile.getparentfile (). exists ()) { Tempfile.getparentfile (). Mkdirs ()//If it is a multilevel file using Mkdirs (), if it is at one level, you can use MkDir ()}if (!tempfile.exists ()) {Tempfile         . CreateNewFile (); } file.transferto (Tempfile);} catch (IllegalStateException e) {baseexception baseexception = new Baseexception (e); Baseexception.seterrormsg ( ERRORMSG); throw baseexception;} Map.put ("sucess", success); Map.put ("Data", Interfaceservice + FilePath + new Date (). GetTime () + tempfile.getname ());} else {map.put ("sucess", Fail), Map.put ("Data", "Image too Big");}} else {map.put ("sucess", Fail), Map.put ("Data", "Image format error"); return map;}

This is the problem I have encountered in my work, and I share it with you, hoping that we will not spend a lot of time on this issue. Thank you

HTML5 Ajax Java Interface upload image

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.