這篇文章就簡單的介紹一個很好用的文件上傳工具,批量帶預覽功能。直接貼代碼吧,都有注釋,很好理解。
HTML頁面
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<c:set var="BASE" value="${pageContext.request.contextPath}"/>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增照片</title>
<script type="text/javascript">
var BASE = "${BASE}";
</script>
<!-- 引用控制層插件樣式 -->
<link rel="stylesheet" href="${BASE}/www/css/upload/zyupload-1.0.0.min.css " type="text/css">
<script type="text/javascript" src="${BASE}/www/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${BASE}/www/js/upload/zyupload-1.0.0.min.js"></script>
</head>
<body>
<input type="hidden" id="boxId" value="${boxId}"/>
<div id="zyupload" class="zyupload"></div>
<script type="text/javascript">
$(function(){
var boxId = $("#boxId").val();
// 初始化插件
$("#zyupload").zyUpload({
width : "650px", // 寬度
height : "400px", // 寬度
itemWidth : "140px", // 文件項的寬度
itemHeight : "115px", // 文件項的高度
url : BASE+"/photo/add/"+boxId, // 上傳文件的路徑
fileType : ["jpg","png","txt","js","exe","gif"],// 上傳文件的類型
fileSize : 51200000, // 上傳文件的大小
multiple : true, // 是否可以多個文件上傳
dragDrop : true, // 是否可以拖動上傳文件
tailor : true, // 是否可以裁剪圖片
del : true, // 是否可以刪除文件
finishDel : false, // 是否在上傳文件完成后刪除預覽
/* 外部獲得的回調接口 */
onSelect: function(selectFiles, allFiles){ // 選擇文件的回調方法 selectFile:當前選中的文件 allFiles:還沒上傳的全部文件
console.info("當前選擇了以下文件:");
console.info(selectFiles);
},
onDelete: function(file, files){ // 刪除一個文件的回調方法 file:當前刪除的文件 files:刪除之后的文件
console.info("當前刪除了此文件:");
console.info(file.name);
},
onSuccess: function(file, response){ // 文件上傳成功的回調方法
console.info("此文件上傳成功:");
console.info(file.name);
console.info("此文件上傳到服務器地址:");
console.info(response);
$("#uploadInf").append("<p>上傳成功,文件地址是:" + response + "</p>");
},
onFailure: function(file, response){ // 文件上傳失敗的回調方法
console.info("此文件上傳失敗:");
console.info(file.name);
},
onComplete: function(response){ // 上傳完成的回調方法
console.info("文件上傳完成");
console.info(response);
}
});
});
</script>
</body>
</body>
</html>
JS和CSS、IMAGES文件下載地址https://page69.ctfile.com/fs/3775069-203728262,自己根據html中的導入,找不到的在eclipse全局搜索
action代碼:根據需求改地址
@RequestMapping(value="/add/{boxId}", method={RequestMethod.POST})
public void addPhotospost(@PathVariable(value="boxId") String boxId, HttpServletRequest request,HttpServletResponse response ) throws IOException {
ServletContext servletContext=request.getSession().getServletContext();
String newFileName="";
PrintWriter out = response.getWriter();
//文件保存目錄路徑
String savePath = "E:/";
//String savePath = this.getServletContext().getRealPath("/") + configPath;
// 臨時文件目錄
String tempPath = servletContext.getRealPath("/") + Constant.dirTemp;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String ymd = sdf.format(new Date());
savePath += "/" + ymd + "/";
//創建文件夾
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
tempPath += "/" + ymd + "/";
//創建臨時文件夾
File dirTempFile = new File(tempPath);
if (!dirTempFile.exists()) {
dirTempFile.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(20 * 1024 * 1024); //設定使用內存超過5M時,將產生臨時文件並存儲於臨時目錄中。
factory.setRepository(new File(tempPath)); //設定存儲臨時文件的目錄。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List items = upload.parseRequest(request);
System.out.println("items = " + items);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(savePath, newFileName);
OutputStream os = new FileOutputStream(uploadedFile);
InputStream is = item.getInputStream();
byte buf[] = new byte[1024];//可以修改 1024 以提高讀取速度
int length = 0;
while( (length = is.read(buf)) > 0 ){
os.write(buf, 0, length);
}
//關閉流
os.flush();
os.close();
is.close();
System.out.println("上傳成功!路徑:"+savePath+"/"+newFileName);
out.print(savePath+"/"+newFileName);
}catch(Exception e){
e.printStackTrace();
}
}else {
String filedName = item.getFieldName();
System.out.println("===============");
System.out.println(new String(item.getString().getBytes("iso-8859-1"),
"utf-8"));
System.out.println("FieldName:"+filedName);
// 獲得裁剪部分的坐標和寬高
System.out.println("String:"+item.getString());
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
效果圖:

