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
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
web.xml
如对本文有疑问, 点击进行留言回复!!
荐 深入理解Java中的BigInteger和 BigDecimal,再也不怕面试了
tomact正常启动,但是在日志文件报错java.lang.NoClassDefFoundError: java/util/logging/Logger
servlet整合quartz:servlet中使用quartz,服务器启动时加载任务
荐 Java——集合中的Map接口通过HashMap类实现一些常用的方法
SpringBoot整合mybatis访问时报错Invalid bound statement (not found)
网友评论