jquery uploadify和apache Fileupload实现异步上传文件示例
jquery uploadify + apache fileupload异步上传文件示例
1、可以限制上传文件大小和类型,理论上任何类型的文件都可以上传(自己根据api配置即可);
2、后台使用apache commons-fileupload-1.3.1.jar作为上传工具包,本示例支持一次性多文件上传;
3、文件上传目录可以任意指定,请在web.xml中配置;
uploadify api 详见http://www.uploadify.com/documentation/
fileuploadservlet
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;
/**
* <h1>apache fileupload文件上传(2014-5-3)</h1>
* <p>1、如果你对本示例感兴趣并想了解更多,欢迎加入java私塾在线学习社区(329232140)</p>
* <p>2、针对这个例子小修小改便可移植到你的实际项目中。</p>
*/
public class fileuploadservlet extends httpservlet {
private static final long serialversionuid = 7579265950932321867l;
// 设置文件默认上传目录(如果你没有在web.xml中配置的话)
private string uploaddir = "c:/"; // 文件上传目录
private string tempuploaddir = "c:/"; // 文件临时存放目录(会话销毁后由监听器自动删除)
/*
* (non-javadoc)
* @see javax.servlet.genericservlet#init()
* 如果在web.xml中配置了文件上传目录则优先使用,判断文件目录是否存在,不存在就创建。
*/
@override
public void init() throws servletexception {
// 获取本项目所在真实硬盘目录
string path = getclass().getprotectiondomain().getcodesource().getlocation().getpath();
path = path.substring(0, path.indexof("web-inf"));
// 判断目标是否存在,不存在就建立
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();
}
// 给变量赋值
this.uploaddir = uploaddir;
this.tempuploaddir = tempuploaddir;
}
/*
* (non-javadoc)
* @see javax.servlet.http.httpservlet#doget(javax.servlet.http.httpservletrequest, javax.servlet.http.httpservletresponse)
* 不接收get方式提交的数据,返回上传失败状态码。
*/
@override
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
this.setresponse(response);
printwriter out = response.getwriter();
out.print("{\"error\":\"-1\""); // 非法提交方式
}
/*
* (non-javadoc)
* @see javax.servlet.http.httpservlet#dopost(javax.servlet.http.httpservletrequest, javax.servlet.http.httpservletresponse)
* 上传文件请求都是通常post提交
*/
@override
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
this.setresponse(response); // 设置响应类型,以便前端解析
printwriter out = response.getwriter();
string result = "";
try {
// 检查本次是否一个文件上传请求
boolean ismultipart = servletfileupload.ismultipartcontent(request);
if (ismultipart) {
diskfileitemfactory factory = new diskfileitemfactory(); // 创建一个工厂基于磁盘的文件项
factory.setrepository(new file(tempuploaddir)); // 配置储存库(确保安全的临时位置时)
servletfileupload upload = new servletfileupload(factory); // 创建一个新的文件上传处理程序
upload.setsizemax(1024 * 1024 * 100); // 设置总体要求尺寸限制(建议前后台分别设置,因为前后台用到了不同的插件)
list<fileitem> items = upload.parserequest(request); // 解析请求
iterator<fileitem> iter = items.iterator(); // 处理上传的项目
while (iter.hasnext()) { //如果是一次性上传多个文件,那这里会分别去保存
fileitem item = iter.next();
if (!item.isformfield()) { // 过滤表单里的非文件类型字段
if (!"".equals(item.getname())) { // 过滤非文件类型的input
string s_name = item.getname(); // 获得原始文件名
int position = s_name.lastindexof(".");
string s_filetype = s_name.substring(position, s_name.length()); // 获得文件后缀
string date = new simpledateformat("yyyymmdd").format(new date());
string s = uploaddir.concat("/").concat(date).concat("/");
//这里按日期分目录保存文件
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); // 拼接返回前端json
out.print(s_resultjson);
} catch (exception e) {
e.printstacktrace();
} finally {
out.flush();
out.close();
}
}
/**
* 拼接json,将保存文件的文件名和日期目录返回给前端(前端可能需要这个路径完成其他表单操作,比如将文件路径存放到数据库)
* @param result json格式的字符串
* @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\""; //上传失败
}
return str;
}
/**
* 设置响应类型contenttype为"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
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery uploadify + apache fileupload异步上传文件示例(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上传文件',
'filesizelimit' : '1024kb',
'filetypeexts' : '*.gif; *.jpg; *.png',
'swf' : '/js/uploadify/uploadify.swf',
'uploader' : '/upload', //这是上传图片的路径,也就是我在web.xml里配置的servlet
'onuploadsuccess' : function(file, data, response) { //图片上传成功后返回数据在这里处理
var ary = eval("(" + data + ")").rows;
for(var i = 0; i < ary.length; i++) {
$("#j_div").append("<img alt='图片' src='/upload/images" + ary[i].name + "' width='200px' height='200px'>");
}
}
});
});
</script>
</head>
<body>
<h2>jquery uploadify + apache fileupload异步上传文件示例(2014-5-3)</h2>
<p>1、可以限制上传文件大小和类型,理论上任何类型的文件都可以上传(自己根据api配置即可);</p>
<p>2、后台使用apache commons-fileupload-1.3.1.jar作为上传工具包,本示例支持一次性多文件上传;</p>
<p>3、文件上传目录可以任意指定,请在web.xml中配置;</p>
<p>4、对于已经上传的图片没有查询到这个页面上,这部分留给你去做吧。</p>
<p>uploadify api 详见http://www.uploadify.com/documentation/</p>
<p style="color: red">*如果你对本示例感兴趣并想了解更多,欢迎加入java私塾在线学习社区(329232140)。</p>
<input id="fileupload" type="file" name="img" multiple="multiple"/>
<div id="j_div"></div>
</body>
</html>
web.xml
<?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>
<servlet-name>fileuploadservlet</servlet-name>
<servlet-class>com.xiaoxing.upload.fileuploadservlet</servlet-class>
<init-param>
<description>文件存放的正式目录,可以自己配置</description>
<param-name>uploaddir</param-name>
<param-value>/upload/images/</param-value>
</init-param>
<init-param>
<description>文件存放的临时目录,可以自己配置,里的文件由下面配置的监听器自动删除。</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>临时文件资源清理,工具包自带,不用我们来写</description>
<listener-class>org.apache.commons.fileupload.servlet.filecleanercleanup</listener-class>
</listener>
</web-app>