Upload images asynchronously using Kindeditor's Uploadbutton
The most frequently used method of uploading images asynchronously is to upload them in an IFRAME. This only needs to refresh the IFRAME. Instead of refreshing the entire page.
kindeditor Text Editor Framework Uploadbutton can help us, no longer need us to write the IFRAME implementation. Very convenient 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= "Change 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 (' Self-defined 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 a picture, such as the following code:
<%@ 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 Folder Path
Stored under the \kindeditor\attached
String Savepath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/cms/";
File Save Folder url/kindeditor/attached/
String Saveurl = Request.getcontextpath () + "/upload/cms/";
Define file extensions that agree to upload
Define file extensions that agree to upload
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");
Agree 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 folders
File Uploaddir = new File (savepath);
if (!uploaddir.isdirectory ()) {
out.println ( GetError ("The Upload folder does not exist. "));
return;
}
//Check folder Write permissions
if (! Uploaddir.canwrite ()) {
out.println (geterror ("Upload folder 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 folder name is incorrect.
"));
Return
}
Create a Directory
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 folder does not exist.
"));
Return
}
Check folder Write permissions
if (!dirfile.canwrite ()) {
Out.println (GetError ("Upload folder 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 ("Upload file extension is not an agreed extension. \ n Just agree with "+ 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
Upload images asynchronously using Kindeditor's Uploadbutton