function Uploadpic () {var options = {url: "/upload/updatepic.action", type: "Post", DataType: "JSON", Success:function (DA TA) {$ ("#allUrl"). attr ("src", Data.url); $ ("#imgUrl"). Val (Data.url);}; $ ("#jvForm"). Ajaxsubmit (options);}
PackageTop.dgoyou.core.controller;ImportJava.io.File;ImportJava.util.UUID;ImportJavax.servlet.http.HttpServletResponse;Importorg.apache.commons.io.FilenameUtils;ImportOrg.json.JSONObject;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.multipart.MultipartFile, @Controller @requestmapping ("/upload") Public classUploadcontroller {//Uploading pictures asynchronously@RequestMapping ("/updatepic") Public voidUpdatepic (multipartfile pic,httpservletresponse response)throwsexception{//get file Original nameString filename =Pic.getoriginalfilename (); //use random string + source picture extension to make a new picture name to prevent the duplicate imageString Newfilename=uuid.randomuuid (). toString (). ReplaceAll ("-", "") + "." +filenameutils.getextension (filename); //Save the file to the picture server ("E:\testpic" the image virtual path can be converted to fastdfs| later | Cloud)Pic.transferto (NewFile ("E:\testpic")); //Jsonobject is a simple to go JSON tool class, but can only be transferred to string, Double,integer,long and other simple types, can not go Pojo, list, set, map, etc.Jsonobject Jsonobject =NewJsonobject (); Jsonobject.put ("url", "/pic/" +newfilename); Response.setcontenttype ("Application/json;charset=utf-8");
Response to the front page response.getwriter (). Write (jsonobject.tostring ()); }}
Ajax asynchronous upload image &springmvc background code