File Upload page
<Div> <inputtype= "File"ID= "File"name= "File"onchange= "ajaxfileupload ();"/> <inputtype= "hidden"ID= "Pic"name= "Pic" /> </Div>
Ajax implementation File Upload function Ajaxfileupload () {var picpath= ""; $.ajaxfileupload ({URL: "). /upload/imageupload ", fileelementid: ' file ', dataType:" JSON ", success:function (data) { $ (" # Picshow "). Append (" ") alert (' success '); picpath=$ ("#pic"). Val () +data.filename+ ","; $ ("#pic"). Val (Picpath); }, error:function (data) { alert ("Upload failed"); } );}
Import Java.io.file;import java.io.ioexception;import Java.util.arrays;import Java.util.hashmap;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.servlet.servletfileupload;import Org.apache.log4j.logger;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.restcontroller;import Org.springframework.web.multipart.commons.commonsmultipartfile;import ease.shopping.util.uuidgenerator;/** * File Upload class * @author Administrator * */@RestController @requestmapping ("/upload") public class Uploadcontroller {private Static final Logger LOG = Logger.getlogger (uploadcontroller.class);p rivate static final hashmap<string, string> Typemap = new hashmap<string, string> ();//settings file allows upload of type static {Typemap.put ("image", "gif,jpg,jpeg,png,bmp"); Typemap.put ("FLash "," swf,flv "); Typemap.put ("Media", "SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB"); Typemap.put ("File", "Doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");} Set file upload size public static long fileSize = 3 * 1024 * 1024;/** * File Upload * * * * @param file * @param request * @return Message:- 1 no file Upload 0 upload success 1 upload failed 2 file exceeds upload size 3 file format error 4 upload file path illegal 5 upload directory no write permission * */@RequestMapping (value = "/imageupload", Me Thod = requestmethod.post) public void Imageupload (@RequestParam ("file") Commonsmultipartfile file, @RequestParam ( Required = False) String Filepre, httpservletrequest request, httpservletresponse response) {log.info ("file name is:" + F Ile.getoriginalfilename ()); if (!file.isempty ()) {//If the file exceeds the set size, the upload if (file.getsize () > FileSize) {backinfo ( Response, False, 2, ""); return;} Gets the file name suffix string originalfilename = File.getoriginalfilename (); String Filesuffix = originalfilename.substring (Originalfilename.lastindexof (".") + 1). toLowerCase ();//String filesuffix= "JPEG";//Determine whether the type of file is within the file type allowed to upload if(! Arrays.aslist (Typemap.get ("file"). Split (",")). Contains (Filesuffix)) {Backinfo (response, False, 3, ""); return;} if (! Servletfileupload.ismultipartcontent (Request)) {Backinfo (response, False,-1, ""); return;} Check the directory of the uploaded files file uploaddir = new file (Sysproperty.base_path), if (!uploaddir.isdirectory ()) {if (!uploaddir.mkdir ()) { Backinfo (response, False, 4, ""); return;}} Whether there is permission to upload if (!uploaddir.canwrite ()) {Backinfo (response, False, 5, ""); return;} New file name string newname = ""; if (null! = Filepre) {newname + = filepre;//corresponding module upload filename prefix} newname +=uuidgenerator.getuuidrand () + "." + filesuffix;try {//create file SaveFile = ' new file ' (Sysproperty.base_path, newname);//Save File File.transferto (SaveFile); /filetranser.savefielbyfilename (file, Uploadpath, newname); Backinfo (response, True, 0, newname);} catch (Exception e) {log.error (E.getmessage (), E); Backinfo (response, False, 1, ""); return;} else {Backinfo (response, False,-1, ""); return;}} /** * Return JSON information * @param response * @param flag * @param message * @param fIlename */private void Backinfo (HttpServletResponse response, Boolean flag, int message,string fileName) {String json = " ";//json=filename;if (flag) {json =" {\ "status\": \ "Success";} else {json = "{\" status\ ": \" error ";} JSON + = "\", \ "filename\": \ "" + FileName + "\", \ "message\": \ "+ message +" \ "}"; try {//response.setcontenttype ("Text/jav Ascript "); Response.setcontenttype (" text/html; Charset=utf-8 "); Response.getwriter (). print (JSON); Log.info (Json.tostring ());} catch (IOException e) {log.error (E.getmessage (), E);}}}
Need to use the JS file link: http://pan.baidu.com/s/1kTMZDQ3 Password: RKOQ
Ajaxfileupload+springmvc File Upload Example