uploadify是一种基于flash的上传控件,很遗憾基于HTML5的是收费版本。该插件支持自动上传及多文件上传。简单记录一下其用法。
首先是前台jsp代码:
<div id="fileQueue">
<input type="file" name="uploadify" id="uploadify" />
<input type="file" name="uploadify" id="uploadify" />
</div>
js代码:
<script type="text/javascript">
$(function() {
$("#uploadify").uploadify({ //初始化函数
'width': 120,
//uploadify v3.1之前的用法
$(function() {
$("#uploadify").uploadify({ //初始化函数
'width': 120,
//uploadify v3.1之前的用法
//uploader:"${pageContext.request.contextPath}common/upload/swf/uploadify.swf",
//script: "${pageContext.request.contextPath}/uploadify.action?random="+Math.random(),
//uploadify v3.1之后的用法
//flash文件位置,包含BROWSE的按钮,点击打开文件选择框
'swf' : '${pageContext.request.contextPath}/common/upload/swf/uploadify.swf',
//后台处理的请求(sevlet)
'uploader': '${pageContext.request.contextPath}/uploadify.action?random='+Math.random(),
//选定文件后是否自动上传,默认false
'auto': true,
//取消按钮图片
'cancelImg': '${pageContext.request.contextPath}/common/upload/image/uploadify-cancel.png',
//与下面的上传文件列表id对应
'queueID': 'fileQueue',
//上传文件的数量
'queueSizeLimit': 8,
//上传文件类型说明
'fileTypeExts': '*.doc;*.docx;*.jpg;*.png',
//设置提交方式,默认为post
'method': 'post',
//设置是否允许多文件上传
'multi': true,
//是否自动将已上传文件删除
'removeCompleted':false,
//浏览按钮上的文字
'buttonText': ' 上传',
//上传文件的大小限制。默认单位kb
'fileSizeLimit' : '2MB',
//当Uploadify初始化过程中检测到当前浏览器不支持flash时触发。
'onFallBack' : function(){
alert("当前浏览器不支持Flash");
},
//当文件即将开始上传时立即触发
'onUploadStart' : function (file) {
alert("id:" + file.id + " -索引:" + file.index + " -文件名称:" + file.name +
" -文件大小:" + file.size + " -文件类型:" + file.type + " -创建日期:" + file.creationdate +
" -修改日期:" + file.modificationdate + " -文件状态:" + file.filestatus);
},
//文件上传队列处理完毕后触发。
'onQueueComplete' : function (stats) {
alert("成功上传的文件数:" + stats.uploadsSuccessful + " -上传出错的文件数:" +
stats.uploadsErrored + " -上传的文件总大小:" + stats.uploadSize);
}
});
});
</script>
//script: "${pageContext.request.contextPath}/uploadify.action?random="+Math.random(),
//uploadify v3.1之后的用法
//flash文件位置,包含BROWSE的按钮,点击打开文件选择框
'swf' : '${pageContext.request.contextPath}/common/upload/swf/uploadify.swf',
//后台处理的请求(sevlet)
'uploader': '${pageContext.request.contextPath}/uploadify.action?random='+Math.random(),
//选定文件后是否自动上传,默认false
'auto': true,
//取消按钮图片
'cancelImg': '${pageContext.request.contextPath}/common/upload/image/uploadify-cancel.png',
//与下面的上传文件列表id对应
'queueID': 'fileQueue',
//上传文件的数量
'queueSizeLimit': 8,
//上传文件类型说明
'fileTypeExts': '*.doc;*.docx;*.jpg;*.png',
//设置提交方式,默认为post
'method': 'post',
//设置是否允许多文件上传
'multi': true,
//是否自动将已上传文件删除
'removeCompleted':false,
//浏览按钮上的文字
'buttonText': ' 上传',
//上传文件的大小限制。默认单位kb
'fileSizeLimit' : '2MB',
//当Uploadify初始化过程中检测到当前浏览器不支持flash时触发。
'onFallBack' : function(){
alert("当前浏览器不支持Flash");
},
//当文件即将开始上传时立即触发
'onUploadStart' : function (file) {
alert("id:" + file.id + " -索引:" + file.index + " -文件名称:" + file.name +
" -文件大小:" + file.size + " -文件类型:" + file.type + " -创建日期:" + file.creationdate +
" -修改日期:" + file.modificationdate + " -文件状态:" + file.filestatus);
},
//文件上传队列处理完毕后触发。
'onQueueComplete' : function (stats) {
alert("成功上传的文件数:" + stats.uploadsSuccessful + " -上传出错的文件数:" +
stats.uploadsErrored + " -上传的文件总大小:" + stats.uploadSize);
}
});
});
</script>
关于web.xml中uploadify servlet的配置:
<!-- 附件上传Servlet -->
<servlet>
<servlet-name>uploadify</servlet-name>
<servlet-class>com.uploadify.java.Servlet.Upload</servlet-class>
<load-on-startup>10</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>uploadify</servlet-name>
<url-pattern>/uploadify.action</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>uploadify</servlet-name>
<servlet-class>com.uploadify.java.Servlet.Upload</servlet-class>
<load-on-startup>10</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>uploadify</servlet-name>
<url-pattern>/uploadify.action</url-pattern>
</servlet-mapping>
后台servlet代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Logger log = Logger.getLogger("sysLog");
String path="";
try{
path = UploadUtil.upload(request, response);
}catch(Exception e){
log.info("ERROR INFO: "+e);
}
log.info("PATH:"+path);
}
Logger log = Logger.getLogger("sysLog");
String path="";
try{
path = UploadUtil.upload(request, response);
}catch(Exception e){
log.info("ERROR INFO: "+e);
}
log.info("PATH:"+path);
}
Upload上传类代码:
public class UploadUtil {
@SuppressWarnings("unchecked")
public static String upload(HttpServletRequest request,HttpServletResponse response) throws Exception {
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
String returnPath=basePath+"uploads/";
String savePath =request.getSession().getServletContext().getRealPath("/")+"uploads\\";
File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
}
Iterator<FileItem> it = fileList.iterator();
String name = "";
String extName = "";
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
long size = item.getSize();
String type = item.getContentType();
if (name == null || name.trim().equals("")) {
continue;
}
// 扩展名格式:
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf("."));
}
File file = null;
do {
// 生成文件名:
name = UUID.randomUUID().toString();
file = new File(savePath + name + extName);
} while (file.exists());
File saveFile = new File(savePath + name + extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return returnPath+name + extName+"#"+savePath+name+extName;
}
}
不需要自动上传的话,只需修改 auto 为 false,然后前台jsp代码如下:
<div id="fileQueue">
<input type="file" name="uploadify" id="uploadify" />
<a href="javascript:$('#uploadify').uploadify('upload', '*')">上传</a>
<a href="javascript:$('#uploadify').uploadify('cancel', '*')">取消上传</a>
</div>
<input type="file" name="uploadify" id="uploadify" />
<a href="javascript:$('#uploadify').uploadify('upload', '*')">上传</a>
<a href="javascript:$('#uploadify').uploadify('cancel', '*')">取消上传</a>
</div>
OK,到这儿基本用法已经解释完了。
需要的组件有:
commons-fileupload-1.2.1.jar
commons-io-2.0.jar
--------三人行必有我师焉。对于别人珍贵的知识结晶,我怀着一颗敬畏的心接纳了。希望有朝一日,我也能结出知识的果实造福后人。