JQuery uploadify + Apache fileupload Asynchronous upload File sample
1, can limit the upload file size and type, theoretically any type of file can be uploaded (their own according to the API configuration can);
2, the backstage use Apache Commons-fileupload-1.3.1.jar as the Upload toolkit, this example supports one-time multiple file uploads;
3, File upload directory can be arbitrarily specified, please configure in the Web.xml;
The Uploadify API is detailed in http://www.uploadify.com/documentation/
Fileuploadservlet
Copy Code code as follows:
Package com.xiaoxing.upload;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.io.UnsupportedEncodingException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.UUID;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.FileItem;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* * <p>1, if you are interested in this example and would like to learn more, welcome to join the Java Private Online learning Community (329232140) </p>
* <p>2, for this example minor changes can be transplanted into your actual project. </p>
*/
public class Fileuploadservlet extends HttpServlet {
Private static final long serialversionuid = 7579265950932321867L;
Set file default upload directory (if you are not configured in Web.xml)
Private String Uploaddir = "c:/"; File upload Directory
Private String Tempuploaddir = "c:/"; File temporary storage directory (automatically deleted by listener after session destruction)
/*
* (Non-javadoc)
* @see Javax.servlet.genericservlet#init ()
* If a file upload directory is configured in Web.xml, it will be used preferentially to determine if the file directory exists and is not created.
*/
@Override
public void Init () throws Servletexception {
Get the real hard drive directory where this project is located
String path = GetClass (). Getprotectiondomain (). Getcodesource (). GetLocation (). GetPath ();
Path = path.substring (0, Path.indexof ("Web-inf"));
To determine whether a target exists or not, establish
String Uploaddir = Path.concat (This.getinitparameter ("Uploaddir"));
String Tempuploaddir = Path.concat (This.getinitparameter ("Tempuploaddir"));
File F_uploaddir = new file (Uploaddir);
File F_tempuploaddir = new file (Tempuploaddir);
if (!f_uploaddir.exists ()) {
F_uploaddir.mkdirs ();
}
if (!f_tempuploaddir.exists ()) {
F_tempuploaddir.mkdirs ();
}
Assigning values to variables
This.uploaddir = Uploaddir;
This.tempuploaddir = Tempuploaddir;
}
/*
* (Non-javadoc)
* @see Javax.servlet.http.httpservlet#doget (javax.servlet.http.HttpServletRequest, Javax.servlet.http.HttpServletResponse)
* Do not receive data submitted by the Get method, return the upload failure status code.
*/
@Override
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
This.setresponse (response);
PrintWriter out = Response.getwriter ();
Out.print ("{\" error\ ": \" -1\ ");//Illegal submission method
}
/*
* (Non-javadoc)
* @see Javax.servlet.http.httpservlet#dopost (javax.servlet.http.HttpServletRequest, Javax.servlet.http.HttpServletResponse)
* Upload file request is usually post submission
*/
@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
This.setresponse (response); Set the response type so that the front-end parsing
PrintWriter out = Response.getwriter ();
String result = "";
try {
Check whether this is a file upload request
Boolean ismultipart = servletfileupload.ismultipartcontent (request);
if (Ismultipart) {
Diskfileitemfactory factory = new Diskfileitemfactory (); Create a factory disk-based file entry
Factory.setrepository (New File (Tempuploaddir)); Configure the repository (to ensure a secure temporary location)
Servletfileupload upload = new Servletfileupload (factory); Create a new file upload handler
Upload.setsizemax (1024 * 1024 * 100); Set the overall requirements size limit (recommended before and after the table is set separately, because the front and back of the platform to use a different plug-in)
list<fileitem> items = upload.parserequest (request); Parsing requests
Iterator<fileitem> iter = Items.iterator (); Handling uploaded Items
while (Iter.hasnext ()) {//If multiple files are uploaded at once, this will be saved separately
Fileitem item = Iter.next ();
if (!item.isformfield ()) {//filter non-File Type field in form
if (! "". Equals (Item.getname ())) {//filter non-file type input
String s_name = Item.getname (); Get the original file name
int position = S_name.lastindexof (".");
String S_filetype = s_name.substring (position, s_name.length ()); Get file suffix
String date = new SimpleDateFormat ("YyyyMMdd"). Format (new date ());
String s = uploaddir.concat ("/"). Concat (date). Concat ("/");
Here, save the file by date
File SF = new file (s);
if (!sf.exists ()) {
Sf.mkdirs ();
}
String S_filepath = S.concat (Uuid.randomuuid (). toString ()). Concat (S_filetype);
File path = new file (S_filepath);
Item.write (path);
result = S_filepath.concat (",");
} else {
result = "";
Break
}
}
}
} else {
result = "";
}
String S_resultjson = This.jointjson (result); Stitching back Front JSON
Out.print (S_resultjson);
catch (Exception e) {
E.printstacktrace ();
finally {
Out.flush ();
Out.close ();
}
}
/**
* Splicing JSON to return the file name and date directory to the front end (the front end may need this path to complete other form operations, such as the file path to the database)
* @param result JSON-formatted string
* @return
* @throws unsupportedencodingexception
*/
private string Jointjson (string result) throws Unsupportedencodingexception {
String str = "";
if (! "". Equals (Result)) {
String rs[] = Result.split (",");
StringBuffer buffer = new StringBuffer ("{\" rows\ ": [");
for (int i = 0; i < rs.length; i++) {
String s_tmpname = rs[i];
S_tmpname = s_tmpname.substring (Uploaddir.length (), s_tmpname.length ());
Buffer.append ("{\" name\ ": \"). Append (S_tmpname). Append ("\"}, ");
}
str = buffer.tostring ();
str = str.substring (0, Str.length ()-1). Concat ("]}");
} else {
str = "{\" error\ ": \" -2\ "";//Upload failed
}
return str;
}
/**
* Set Response type contenttype to "Application/x-json"
* @param response
*/
private void Setresponse (HttpServletResponse response) {
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Application/json;charset=utf-8");
Response.setheader ("Cache-control", "No-cache");
}
}
Test_upload.html
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>jquery uploadify + Apache fileupload Asynchronous Upload File sample (2014-5-3) </title>
<link rel= "stylesheet" type= "Text/css" href= "/js/uploadify/uploadify.css" >
<script src= "/js/jquery-1.9.0.js" ></script>
<script src= "/js/uploadify/jquery.uploadify.min.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ (' #fileupload '). Uploadify ({
' method ': ' Post ',
' ButtonText ': ' Flash upload file ',
' Filesizelimit ': ' 1024KB ',
' filetypeexts ': ' *.gif; *.jpg; *.png ',
' swf ': '/js/uploadify/uploadify.swf ',
' Uploader ': '/upload ',//This is the path to the uploaded image, which is the servlet I configured in Web.xml.
' Onuploadsuccess ': function (file, data, response) {//image uploaded successfully after return data processed here
var ary = eval ("+ Data +")). Rows;
for (var i = 0; i < ary.length; i++) {
$ ("#J_div"). Append ("}
}
});
});
</script>
<body>
<p>1, can limit upload file size and type, theoretically any kind of file can upload (oneself according to API configuration can);</p>
<P>2, backstage use Apache Commons-fileupload-1.3.1.jar as the Upload toolkit, this example supports one-time multiple file uploads;</p>
<p>3, File upload directory can be arbitrarily specified, please configure;</p> in Web.xml
<p>4, for the uploaded images have not been queried on this page, this part is left to you to do it. </p>
The <p>uploadify API is detailed in http://www.uploadify.com/documentation/</p>
<p style= "color:red" >* if you are interested in this example and want to learn more, welcome to join the Java Private Online learning Community (329232140). </p>
<input id= "FileUpload" type= "File" Name= "img" multiple= "multiple"/>
<div id= "J_div" ></div>
</body>
Xml
Copy Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" Metadata-complete= "true" version= "3.0" >
<welcome-file-list>
<welcome-file>test_upload.html</welcome-file>
</welcome-file-list>
<servlet>
<description> servlet</description> to handle the upload operation
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.xiaoxing.upload.FileUploadServlet</servlet-class>
<init-param>
<description> files stored in the official directory, you can configure their own </description>
<param-name>uploadDir</param-name>
<param-value>/upload/images/</param-value>
</init-param>
<init-param>
<description> files stored in the temporary directory, you can configure their own files in the following configured by the listener automatically deleted. </description>
<param-name>tempUploadDir</param-name>
<param-value>/upload/temp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
<listener>
<description> Temporary file resource cleanup, tool pack from the belt, do not need us to write </description>
<listener-class>org.apache.commons.fileupload.servlet.FileCleanerCleanup</listener-class>
</listener>
</web-app>