Uploadify是JQuery的一个上传插件,实现的效果非常不错。
支持批量上传;
带进度显示;
判断文件大小;
下面分别使用commons-fileupload 和struts2来实现一个简单的上传功能。
1,先介绍前台
首先从官网下载Uploadify,本实例使用的uploadify-v3.1
目录结构:
index.jsp页面,采用commons-fileupload方式上传
<%@ page language="java" contentType="text/html; charset=gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Upload</title>
<!--装载文件-->
<link href="uploadify-v3.1/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="uploadify-v3.1/jquery.uploadify-3.1.js"></script>
<script type="text/javascript" src="uploadify-v3.1/swfobject.js"></script>
<!--ready事件-->
<script type="text/javascript">
$(document).ready(function () {
$("#uploadify").uploadify({
'swf': 'uploadify-v3.1/uploadify.swf',
'uploader':'scripts/uploadify',
//'script':'upload!doUpload.action?name=yangxiang',
//'script': 'servlet/Upload?name=yangxiang',
//'cancel' : 'uploadify-v3.1/uploadify-cancel.png',
'queueID' : 'fileQueue', //和存放队列的DIV的id一致
//'fileDataName': 'fileupload', //必须,和以下input的name属性一致
'auto' : false, //是否自动开始
'multi': true, //是否支持多文件上传
'buttonText': 'BROWSE', //按钮上的文字
'simUploadLimit' : 1, //一次同步上传的文件数目
//'sizeLimit': 19871202, //设置单个文件大小限制,单位为byte
'fileSizeLimit' : '6000MB',
'queueSizeLimit' : 10, //队列中同时存在的文件个数限制
//'fileTypeExts': '*.jpg;*.gif;*.jpeg;*.png;*.bmp;*.iso',//允许的格式
//'fileTypeDesc': '支持格式:jpg/gif/jpeg/png/bmp/iso.', //如果配置了以下的'fileExt'属性,那么这个属性是必须的
'onUploadSuccess': function ( fileObj, response, data) {
alert("文件:" + fileObj.name + "上传成功");
},
'onUploadError': function(event, queueID, fileObj) {
alert("文件:" + fileObj.name + "上传失败");
},
'onCancel': function(event, queueID, fileObj){
alert("取消了" + fileObj.name);
}
});
});
</script>
</head>
<body>
<div id="fileQueue" style="width: 30%"></div>
<input type="file" name="file" id="uploadify" />
<p>
<a href="javascript:jQuery('#uploadify').uploadify('upload','*')">开始上传</a>
<a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a>
<a href="upload-struts2.jsp">struts2上传</a>
</p>
</body>
</html>
upload-struts2.jsp页面采用struts2方式上传
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="uploadify-v3.1/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="uploadify-v3.1/jquery.uploadify-3.1.js"></script>
<script type="text/javascript" src="uploadify-v3.1/swfobject.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#file").uploadify({
'swf' : '${pageContext.request.contextPath}/uploadify-v3.1/uploadify.swf',
'uploader' : 'controlor/upload.action',//servlet的路径或者.jsp 这是访问servlet 'scripts/uploadif'
'queueID' : 'fileQueue', //和存放队列的DIV的id一致
'auto' : false, //是否自动开始
'multi': false, //是否支持多文件上传
'buttonText': '选择文件', //按钮上的文字
'simUploadLimit' : 1, //一次同步上传的文件数目
'fileSizeLimit' : '1GB',
'queueSizeLimit' : 1, //队列中同时存在的文件个数限制
// 'formData' :{'path':path}, // 多个参数用逗号隔开 'name':$('#name').val(),'num':$('#num').val(),'ttl':$('#ttl').val()
'fileObjName' : 'file',//和input的name属性值保持一致就好,Struts2就能处理了
'onSelect' :function(file)
{
$("#a_upload").show();
},
'onUploadSuccess': function ( fileObj, response, data) {
var value = response ;
if("fail" == value)
{
$("#a_upload").hide();
alert("文件:" + fileObj.name + "上传失败");
}else if("exist" == value)
{
$("#a_upload").hide();
alert(fileObj.name + "文件名重复");
}else if("existBlank" == value)
{
$("#a_upload").hide();
alert(fileObj.name + "文件名存在空格");
}else if("outOfSize" == value)
{
$("#a_upload").hide();
alert("超出容量大小");
}else
{
alert("文件:" + fileObj.name + "上传成功");
//window.location.href="${pageContext.request.contextPath}/controlor/controlorCloudStorage.html"
}
},
'onUploadError': function(event, queueID, fileObj,errorObj) {
if (errorObj.type === "File Size"){
alert('超过文件上传大小限制(1G)!');
return;
}
alert("文件:" + fileObj.name + "上传失败");
},
'onCancel': function(event, queueID, fileObj){
alert("取消了" + fileObj.name);
}
});
});
</script>
<style type="text/css">
body {
margin:0;
padding:0;
}
#fileUploader{
float:left;
}
</style>
</head>
<body>
<table width="100%">
<tr>
<td valign="middle">
<div id="fileQueue" style="margin-bottom:10px;"></div>
<input type="file" name="file" id="file"/>
<input type="button" value="上传" οnclick="javascript:jQuery('#file').uploadify('upload','*')" id="a_upload" />
<div style="padding-top:10px; clear:both"><font color="ff6600">注:单个文件1G以内,同一目录下文件名不能相同</font></div>
</td>
</tr>
</table>
</body>
</html>
2,后台实现
commons-fileupload方式:
Uploadify.java:
package com.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
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 org.apache.commons.fileupload.util.Streams;
public class Uploadify extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* 实现多文件的同时上传
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//设置接收的编码格式
request.setCharacterEncoding("UTF-8");
Date date = new Date();//获取当前时间
SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");
String newfileName = sdfFileName.format(date);//文件名称
String fileRealPath = "";//文件存放真实地址
String fileRealResistPath = "";//文件存放真实相对路径
//名称 界面编码 必须 和request 保存一致..否则乱码
String name = request.getParameter("name");
String firstFileName="";
// 获得容器中上传文件夹所在的物理路径
String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + sdfFolder.format(date) +"\\";
System.out.println("路径" + savePath);
File file = new File(savePath);
if (!file.isDirectory()) {
file.mkdir();
}
try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
// 获取多个上传文件
List fileList = fileList = upload.parseRequest(request);
// 遍历上传文件写入磁盘
Iterator it = fileList.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
// 如果item是文件上传表单域
// 获得文件名及路径
String fileName = item.getName();
if (fileName != null) {
firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);
String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀名
fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址
BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流
Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹
//上传成功,则插入数据库
if (new File(fileRealPath).exists()) {
//虚拟路径赋值
fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);
//保存到数据库
System.out.println("保存到数据库:");
System.out.println("name:"+name);
System.out.println("虚拟路径:"+fileRealResistPath);
}
}
}
} catch (FileUploadException ex) {
ex.printStackTrace();
System.out.println("没有上传文件");
return;
}
response.getWriter().write("1");
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
struts2方式实现:
package com.struts;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ControlorAction extends ActionSupport {
private File file;
private String fileFileName;
private String fileContentType;
private String path = "";
private String errorCode = "";
String msg = "";
/**
* 控制台-云存储,上传文件操作
*
* @return
*/
public void upload() {
String result = "fail";
HttpServletResponse response = null;
try {
response = ServletActionContext.getResponse();
if (null != file) {
String targetDirectory = ServletActionContext
.getServletContext().getRealPath("/uploads");
String targetFileName = generateFileName(fileFileName);
File target = new File(targetDirectory, targetFileName);
if (!file.exists()) {
// 处理文件大小为0kb的情况
file = new File(file.getPath());
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(" ");
fileWriter.flush();
fileWriter.close();
}
FileUtils.copyFile(file, target);
result = "success";
}
} catch (Exception e) {
e.printStackTrace();
}
try {
response.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成文件名
*
* @param fileName
* @return
*/
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
/**
* 文件大小换上为bite
*
* @param s
* @return
*/
private long getFileSizeByBite(String s) {
long size = 0;
size = Long.parseLong(s) * 1073741824;
/*
* if (s.lastIndexOf("G") != -1 || s.lastIndexOf("g") != -1) { s =
* s.substring(0, s.length() - 1); size = Long.parseLong(s) *
* 1073741824; } else if (s.lastIndexOf("M") != -1 || s.lastIndexOf("m")
* != -1) { s = s.substring(0, s.length() - 1); size = Long.parseLong(s)
* * 1048576; } else if (s.lastIndexOf("T") != -1 || s.lastIndexOf("t")
* != -1) { s = s.substring(0, s.length() - 1); size = Long.parseLong(s)
* * 1024 * 1073741824; }
*/
return size;
}
public String formetFileSize(long fileS) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
}