Upload images asynchronously using Kindeditor's Uploadbutton
The most common way to upload images asynchronously is to upload them in an IFRAME, so that you only need to refresh the IFRAME without refreshing the entire page.
kindeditor Text Editor Framework Uploadbutton can help us to achieve, no longer need to write our own IFRAME implementation, easy to use.
HTML section:
.....
<input class= "" type= "text" name= "Beautytown.img_0" id= "Img_url_0" value= "" readonly= "ReadOnly"/>
<input type= "button" id= "Uploadbutton_0" value= "Modify picture 1"/>
.....
JS section:
.....
Kindeditor.ready (function (K) {
$ ("input[id^= ' Uploadbutton_ ')"). each (function (i,v) {
var obj = this;
var index=i;
var Uploadbutton = K.uploadbutton ({
Button:obj,
FieldName: ' Imgfile ',
URL: ' upload_json.jsp ',
Afterupload:function (data) {
if (data.error = = = 0) {
var url = k.formaturl (data.url, ' absolute ');
K (' #img_url_ ' +index). val (URL);
} else {
alert (data.message);
}
},
Aftererror:function (str) {
Alert (' Custom error message: ' + str ');
}
});
Uploadbutton.fileBox.change (function (e) {
Uploadbutton.submit ();
});
});
});
.....
A fuzzy filter is used in the JS code to bind multiple buttons.
' Upload_json.jsp ' is the action that handles uploading pictures, the code is as follows:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
<%@ page import= "java.util.*,java.io.*"%>
<%@ page import= "Java.text.SimpleDateFormat"%>
<%@ page import= "org.apache.commons.fileupload.*"%>
<%@ page import= "org.apache.commons.fileupload.disk.*"%>
<%@ page import= "org.apache.commons.fileupload.servlet.*"%>
<%@ page import= "org.json.simple.*"%>
<%@ page import= "Org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
<%
File Save directory path
Stored under the \kindeditor\attached
String Savepath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/cms/";
File Save Directory url/kindeditor/attached/
String Saveurl = Request.getcontextpath () + "/upload/cms/";
Define the file extensions that are allowed to be uploaded
Define the file extensions that are allowed to be uploaded
hashmap<string, string> extmap = new hashmap<string, string> ();
Extmap.put ("image", "gif,jpg,jpeg,png,bmp");
Extmap.put ("Flash", "swf,flv");
Extmap.put ("Media", "SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB");
Extmap.put ("File", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
Allow maximum upload file size Struts.xml struts.multipart.maxsize=3g
Long maxSize = 3000000000l;
Response.setcontenttype ("text/html; Charset=utf-8 ");
if (! Servletfileupload.ismultipartcontent (Request)) {
Out.println (GetError ("Please select File. "));
Return
}
Check Catalog
File Uploaddir = new file (Savepath);
if (!uploaddir.isdirectory ()) {
Out.println (GetError ("The upload directory does not exist. "));
Return
}
Check Directory Write permissions
if (!uploaddir.canwrite ()) {
Out.println (GetError ("Upload directory does not have write permission.) "));
Return
}
String dirName = Request.getparameter ("dir");//image
if (DirName = = null) {
DirName = "image";
}
if (!extmap.containskey (DirName)) {
Out.println (GetError ("The directory name is incorrect. "));
Return
}
Create a folder
Savepath + = DirName + "/";
Saveurl + = DirName + "/";
File Savedirfile = new file (Savepath);
if (!savedirfile.exists ()) {
Savedirfile.mkdirs ();
}
SimpleDateFormat SDF = new SimpleDateFormat ("YyyyMMdd");
String ymd = Sdf.format (New Date ());
Savepath + = Ymd + "/";
Saveurl + = Ymd + "/";
File Dirfile = new file (Savepath);
if (!dirfile.exists ()) {
Dirfile.mkdirs ();
}
if (!dirfile.isdirectory ()) {
Out.println (GetError ("The upload directory does not exist. "));
Return
}
Check Directory Write permissions
if (!dirfile.canwrite ()) {
Out.println (GetError ("Upload directory does not have write permission. "));
Return
}
Multipartrequestwrapper wrapper = (multipartrequestwrapper) request;
Get the uploaded file name
String fileName = wrapper.getfilenames ("Imgfile") [0];//imgfile,imgfile,imgfile
Get file filter
File File = Wrapper.getfiles ("imgfile") [0];
Check extension
String Fileext = filename.substring (Filename.lastindexof (".") + 1). toLowerCase ();
if (! Arrays.<string>aslist (Extmap.get (DirName). Split (",")). Contains (Fileext)) {
Out.println (GetError ("The upload file extension is not allowed. \ n only allow "+ extmap.get (dirName) +" format. "));
Return
}
Check File size
if (File.length () > MaxSize) {
Out.println (GetError ("Upload file size exceeds limit. "));
Return
}
Refactoring the name of the uploaded picture
SimpleDateFormat df = new SimpleDateFormat ("Yyyymmddhhmmss");
String newimgname = Df.format (New Date ()) + "_"
+ New Random (). Nextint (+) + "." + Fileext;
byte[] buffer = new byte[1024];
Get file output stream
FileOutputStream fos = new FileOutputStream (Savepath + "/" + newimgname);
Gets the current file input stream in memory
InputStream in = new FileInputStream (file);
try {
int num = 0;
while (num = in.read (buffer)) > 0) {
Fos.write (buffer, 0, num);
}
} catch (Exception e) {
E.printstacktrace (System.err);
} finally {
In.close ();
Fos.close ();
}
Sent to KE
Jsonobject obj = new Jsonobject ();
Obj.put ("error", 0);
Obj.put ("url", Saveurl + "/" + newimgname);
Zswz/attached/image/20111129/image 20111129195421_593.jpg
Out.println (Obj.tojsonstring ());
%>
<%!
private string GetError (String message) {
Jsonobject obj = new Jsonobject ();
Obj.put ("Error", 1);
Obj.put ("message", message);
return obj.tojsonstring ();
}
%>
The jar packages used in the background are:
Commons-fileupload-1.2.2.jar
Json_simple-1.1.jar
Struts2-core-2.1.8.1.jar
such as