Idea: onchange () event triggers an asynchronous request, JS will successfully return the address of the picture after the dynamic write
JSP page: Outer one form with ID MyForm
<pre name= "code" class= "HTML" > <a name= "Uploadimgs" id= "Uploadimgs" ></a> <p>< Label><samp>*</samp> Upload product image (xx size): </label><span id= "UploadImgTip1" class= "Orange" > Note: The size picture must be 90x150. </span></p> <p><label></label><input type= ' file ' id= ' imgsize1file ' name= ' Imgsize1file ' class= "file" Onchange= ' Submitimgsize1upload () '/><span class= ' pos ' id= ' Imgsize1filespan ' > Please upload the size of the picture no more than 3mb</span> <input type= ' hidden ' id= ' imgSize1 ' name= ' imgSize1 ' value= ' reg= ' "^.+$" tip= "Pro! You forgot to upload the product picture. "/></p>
JS function
function Submitimgsize1upload () {var option = {url: ' ${path}/upload/upload.do ',//Submit the form using AJAX, the URL is in option type: ' Post ', DataType: "Text",//Do not write Datetypedata:{filename: ' Imgsize1file '},success:function (responsetext) {// Parse the string into a JSON object var obj = $.parsejson (responsetext); $ ("#imgSize1ImgSrc"). attr ("src", Obj.realpath); $ ("#imgSize1"). val (Obj.relativepath);},error:function () {Alert ("system error");}}; $ ("#myForm"). Ajaxsubmit (option);}
Control layer:
Import com.sun.jersey.api.client.Client;
Import Com.sun.jersey.api.client.WebResource;
@RequestMapping ("/upload.do") public void upload (String fileName, httpservletrequest request, printwriter out) { Multiparthttpservletrequest Mr = (multiparthttpservletrequest) request; Commonsmultipartfile CFile = (commonsmultipartfile) mr.getfile (fileName); byte[] Fbyte = Cfile.getbytes (); String imageName = ""; SimpleDateFormat format = new SimpleDateFormat ("Yyyymmddhhmmsssss"); imageName = Format.format (New Date ()); Random random = new random (), for (int i =0; i < 3; i++) {imageName = ImageName + random.nextint (10);} String raginalfilename = Cfile.getoriginalfilename (); String suffixname = raginalfilename.substring (Raginalfilename.lastindexof (".")); /Create Client clients = Client.create ();//The absolute path of the picture on the picture server string imagePath = ecpsconstants.upload_path+ "/upload/" + Imagename+suffixname; WebResource resource = Client.resource (ImagePath);//Put the picture on the image server Resource.put (String.class, fbyte); String result = "{\" realpath\ ": \" "+imagepath+" \ ", \" relativepath\ ": \" "+"/upload/"+imagename+suffixname+" \ "}"; o Ut.write (resULT); Out.close ();}
Jsp+ajax+springmvc image upload immediately back to display e-commerce