如何使用
1.下载uploadify(http://www.uploadify.com/)
2.创建一个web项目
3. 添加项目所需的jar包commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar
4.然后写写前端代码如下:
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传示范</title>
<!--装载文件-->
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="scripts/swfobject.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
<!--ready事件-->
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
'uploader' : 'servlet/Upload',//后台处理的请求
'swf' : 'scripts/uploadify.swf',
'cancelImg' : 'images/uploadify-cancel.png',
'folder' : 'uploads', //您想将文件保存到的路径
'queueID' : 'fileQueue', //queueID :文件队列的ID,该ID与存放文件队列的div的ID一致
'queueSizeLimit' : 999, //queueSizeLimit :当允许多文件生成时,设置选择文件的个数,默认值:999 。
'fileDesc' : 'rar文件或zip文件',
'fileExt' : '*.rar;*.zip', //fileExt :设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。
'auto' : false, //设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传
'multi' : true, //multi :设置为true时可以上传多个文件。
'simUploadLimit' : 5, //simUploadLimit :允许同时上传的个数 默认值:1
'buttonText' : '选择文件',
'progressData' : 'speed', //('percentage:百分比' or 'speed':速度) 进度显示类型
'removeCompleted' : true, //完成上传的是否自动消失
//'buttonImage' :'images/button.jpg', //按钮图片
'removeTimeout' :0, //上传完成进度条消失的时间
'height':25, //按钮高度
'width':80,
'buttonClass':'button',
//'buttonCursor':'arrow'
'onCancel': funCancel, //当用户取消上传时
'onUploadComplete': funComplete, //完成上传任务
'OnError': funError, //上传发生错误时
'onFallback' :onFallback,
'onUploadSuccess' : onUploadSuccess, //文件上传成功时
'onQueueComplete' : onQueueComplete //选中所有文件上传完成
});
$("#a").click(function(){
$("#uploadify").uploadify('upload','*');
$("#uploadify").css({'visibility': 'hidden'});
});
$("#b").click(function(){
$("#uploadify").uploadify('cancel','*');
});
//用户取消函数
function funCancel(event, ID, fileObj, data) {
//jBox.tip('您取消了' + fileObj.name + '操作', 'info');
alert("取消");
return;
}
//图片上传发生的事件
function funComplete(event, ID, fileObj, response, data) {
if (response == 0) {
//jBox.tip('图片' + fileObj.name + '操作失败', 'info');
return;
}
//$("#pic").attr("src", "../uploads/" + response).height(200).width(300);
//jBox.tip('图片' + fileObj.name + '操作成功', 'info');
return;
}
//上传发生错误时。
function funError(event, ID, fileObj, errorObj) {
//jBox.tip(errorObj.info);
alert("上传错误");
return;
}
//检测FLASH失败调用
function onFallback(){
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
return;
}
//上传到服务器,服务器返回相应信息到data里
function onUploadSuccess(file, data, response){
//$('#uploadify').uploadify('upload');
//alert(data);
//$("#pic1").append("<img title=\""+file.name+"\"alt=\""+file.name+"\" style=\"width:80px;height:50px;\" src=\"uploads/"+data+"\" />");
//alert(data);
$("#pic1").append("<a target=\"_blank\" href='uploads/"+data+"'>"+file.name+"</a>");
}
//所有文件上传完成是执行
function onQueueComplete(){
$("#uploadify").css({'visibility': 'visible'});
}
//-------------------------------------------------------------------
//弹出层
var mask = "";
function createMask(){
if(mask==""){
mask=document.createElement("div");
}
var W=$(document).width();
var H=$(document).height();
mask.id="mask";
mask.style.cssText="position:absolute;z-index:100;width:"+W+"px;height:"+H+"px;background:black;filter:alpha(opacity=60);opacity:0.6;top:0;left:0;";
$("body").append(mask).show();
}
$("a").click(function(){
createMask();
$("#msg1").show();
});
$("#msg1closeBtn").click(function(){
$("#mask").hide();
$("#msg1").hide();
});
});
</script>
<style type="text/css">
.button{
width:50px;height:20px;background:url(images/button.jpg);
text-align:center;float:right;color:#FFF
}
</style>
</head>
<body>
<div id='pic1'></div>
<a href="javascript:void(0)">上传文件</a>
<div id="msg1" class="lightBox" style="position: absolute; left: 50%; top: 50%; z-index: 102; margin-left: -320px; margin-top: -212.5px;display:none;">
<div id="msg1_head" class="Boxheader" style="height:46px;position:relative;">
<div class="headerL" id="msg1headerL" style="width: 600px;background:url(images/lightbox-header.png) no-repeat left 0;height:46px;padding:0 0 0 20px;float:left;">
<a style="float:right;background:url(images/lightbox-close.png) no-repeat 0 center;display:inline-block;height:46px;width:16px;" title="关闭" id="msg1closeBtn"></a>
</div>
<div class="headerR" style="background:url(images/lightbox-header.png) no-repeat right 0;float:left;width:20px;height:46px;"></div>
</div>
<div id="msg1_body" class="Boxbody" style="overflow:hidden;position:relative;">
<div class="BodyL" id="msg1BodyL" style="height: 300px; width: 600px;background:url(images/lightbox-body.png) repeat-y left 0;padding:10px 0 10px 20px;float:left;">
<div style="width:600px;height:300px;border:groove #000 1px;; overflow:scroll;" id="fileQueue"></div>
</div>
<div id="msg1BodyR" style="height: 320px;background:url(images/lightbox-body.png) repeat-y right 0;float:left;width:20px;"></div>
</div>
<div id="msg1_footer" class="Boxfooter" style="position:relative;height:59px;display:inline-block;float:right;margin:0px 10px 0 0;">
<div class="FooterL" id="msg1FooterL" style="width: 600px;height:39px;background:url(images/lightbox-footer.png) no-repeat left 0;padding:10px 0 10px 20px;float:left;">
<a href="javascript:void(0)"style="display:inline-block;margin:0px 15px 0 0;width:80px;height:25px;text-decoration:none;background:url(images/button.jpg) no-repeat;color:#FFF;text-align:center;line-height:25px;" id="b" title="取消">取消所有</a>
<a href="javascript:void(0)"style="display:inline-block;float:left;margin:0px 10px 0 0;width:80px;height:25px;text-decoration:none;background:url(images/button.jpg) no-repeat;color:#FFF;text-align:center;line-height:25px;" id="a" title="开始上传">开始上传</a>
<input type="file" name="uploadify" id="uploadify" style="display:inline-block;float:left;margin:5px 10px 0 0;height:30px;" />
</div>
<div class="FooterR" style="float:left;width:20px;background:url(images/lightbox-footer.png) no-repeat right 0;height:59px;"></div>
</div>
</div>
</body>
</html>
5.接下来就是写我们的服务器代码创建一个servlet Upload,java代码如下
package upload;
import java.io.File;
import java.io.IOException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import biz.UploadBiz;
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
//UploadBiz up = new UploadBiz();
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String savePath = this.getServletConfig().getServletContext()
.getRealPath("");
savePath = savePath + "/uploads/";
File f1 = new File(savePath);
System.out.println(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
@SuppressWarnings("rawtypes")
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
return;
}
Iterator<FileItem> it = fileList.iterator();
String name = "";
String extName = "";
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
System.out.println("文件名:" + name);
String name1 = name;
long size = item.getSize();
String type = item.getContentType();
System.out.println(size + " " + type);
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);
System.out.println(name+extName);response.getWriter().write(name + extName);
try {
//up.addInfo(name1, name+extName);
} catch (Exception e) {
e.printStackTrace();
}
} while (file.exists());
File saveFile = new File(savePath + name + extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//response.getWriter().print(name + extName);
//response.getWriter().write(name + extName);
}
}
6.最后就是修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>upload.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/servlet/Upload</url-pattern>
</servlet-mapping>
</web-app>
项目结构
代码运行效果