最近使用org.apache.commons.fileupload,在SpringMVC架構下做了一個帶進度條上傳檔案功能,做個備忘,順便分享給大家。
上次前的效果為:
上次後的效果:
項目目錄結構為:
前端代碼為:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html >
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" >
<title>檔案上傳</title>
<meta name="description" content="overview & stats" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="static/css/bootstrap.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />
<link href="static/css/bootstrap-responsive.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />
<link href="static/css/font-awesome.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />
<!-- 引入 -->
<script src="static/js/jquery-1.9.1.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
<script src="static/js/ace-elements.min.js"></script>
<script src="static/js/ace.min.js"></script>
<script src="static/js/bootstrap-datepicker.min.js" type="text/javascript" ></script><!-- 日期框 -->
<script src="static/js/bootbox.min.js" type="text/javascript" ></script><!-- 确認視窗 -->
<script src="static/js/jquery.tips.js" type="text/javascript" ></script><!--提示框-->
<script type="text/javascript">
function errInfo(fieldId,fieldInfo){
$(fieldId).tips({side:3,msg:fieldInfo,bg:'#AE81FF',time:2});
$(fieldId).focus();
}
</script>
</head>
<script type="text/javascript">
var count=100;
var original=new Array;//原始數組
//給原始數組original指派
for (var i=0;i<count;i++){
original[i]=i;
}
function add(){
var file1 = $("#file1").val();
if(file1 == null || file1 == ""){
$("#file1").tips({side:3,msg:'軟體必須上傳!',bg:'#AE81FF',time:2});
$("#file1").focus();
return false;
}
var file2 = $("#file2").val();
if(file2 == null || file2 == ""){
$("#file2").tips({side:3,msg:'首頁必須上傳!',bg:'#AE81FF',time:2});
$("#file2").focus();
return false;
}
if(window.confirm('您确認要送出上述資料資訊嗎?')){
document.getElementById("form").action="<%=basePath%>upload/save.do";
document.getElementById("form").submit();
var eventFun = function(){
$.ajax({
type: 'GET',
url: '<%=basePath%>upload/process.do',
data: {},
dataType: 'json',
success : function(data){
$('#proBar').css('width',data.rate+''+'%');
$('#proBar').empty();
$('#proBar').append(data.show);
if(data.rate == 100){
window.clearInterval(intId);
cancel();
}
}});};
var intId = window.setInterval(eventFun,500);
}
}
function fileType(obj,objIndex){
var uploadfile = $(obj).val();
var filename=$(obj).attr("name");
if("filetmp"==filename){
$(obj).attr("name","file"+new Date().getTime());
}
if(uploadfile!=""){
var imgSize=$(obj).context.files[0].size/1024;//得到圖檔的大小(機關kb)
var types = [ "rar", "zip", "iso"];
var fileTypsInfo=parentClass+"素材隻支援rar,zip,iso格式!";
var fileMaxSize=100;//單元M
if(objIndex==1){
types = ["exe", "rar", "zip", "iso"];
fileTypsInfo=parentClass+"素材隻支援 exe,rar,zip,iso格式!";
}else if(objIndex==2){
types = ["jpg", "png", "bmp"];
fileTypsInfo=parentClass+"預覽圖隻支援jpg,png,bmp格式!";
}
var ext = uploadfile.substring(uploadfile.length-3).toLowerCase();
var sing = false;
for(var i=0; i<types.length;i++){
if (ext==types[i]){
sing = true;
}
}
if(!sing){
$(obj).val("");
alert(fileTypsInfo);
return false;
}
if(imgSize>1024*fileMaxSize){
$(obj).val("");
alert("隻允許上傳小于"+fileMaxSize+"M的圖檔!");
return false;
}if(imgSize<5){
$(obj).val("");
alert("隻允許上傳大于5K的檔案!");
return false;
}
}
return true;
}
function selectfile1(){
document.getElementById("file1").click();
}
</script>
<body>
<div class="container-fluid" id="main-container">
<div id="page-content" class="clearfix">
<div class="row-fluid">
<div class="row-fluid">
<div>
<form action="<%=basePath%>upload/save.do" method="post" id="form" enctype="multipart/form-data" target="uploadf">
<table align="center" style="width: 100%;">
<tr align="left">
<td align="right"><font color="red">*</font>上傳軟體:</td>
<td align="left">
<input name="file1" id="file1" type="file" οnchange="fileType(this,1)"/>
</td>
</tr>
<tr align="left">
<td align="right"><font color="red">*</font>上傳首頁圖檔:</td>
<td align="left">
<input name="file2" id="file2" type="file" οnchange="fileType(this,2)"/>
</td>
</tr>
<tr align="left" id="addrow" style="display:none;">
<td align="right"></td>
<td align="left">
<input name="filetmp" id="file1" type="file" οnchange="fileType(this,1)"/>
<input name="filetmp" id="file2" type="file" οnchange="fileType(this,2)"/>
</td>
</tr>
<tr align="left">
<td align="right">上傳進度:</td>
<td align="left">
<div class="progress progress-success progress-striped" style="width:100%">
<div id = 'proBar' class="bar" style="width: 0%"></div>
</div>
</td>
</tr>
<tr align="left">
<td align="left"></td>
<td align="left">
<input type="button" value="确認" οnclick="javacript:add();" style="width: 80px;height: 30px;border-top-width: -10px;" class='btn btn-lg btn-danger' />
</td>
</tr>
</table>
<iframe name="uploadf" style="display:none"></iframe>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
後端代碼為:
@RequestMapping(value = "/save", method = { RequestMethod.GET,
RequestMethod.POST })
public ModelAndView save(HttpServletRequest request) throws IllegalStateException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
return toshow(request);
}
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
final HttpSession hs = request.getSession();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int pItems) {
ProcessInfo pri = new ProcessInfo();
pri.itemNum = pItems;
pri.readSize = pBytesRead;
pri.totalSize = pContentLength;
pri.show = pBytesRead+"/"+pContentLength+" byte";
pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);
hs.setAttribute("proInfo", pri);
}
});
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
String curpath = request.getSession().getServletContext().getRealPath("static/data/3DModel");
int fileNum = 1;
// 檔案目錄
String filepath = "/" + DateUtil.getFilePath() + "/";
File firstFolder = new File(curpath + filepath); // 一級檔案夾
if (!firstFolder.exists()) { // 如果一級檔案夾存在,則檢測二級檔案夾
firstFolder.mkdir();
}
while (iter.hasNext()) {
FileItem fileItem = (FileItem) iter.next();
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
if ("keywords".equals(name)) {
//
}
} else {
if (fileItem != null) {
// 取得目前上傳檔案的檔案名稱
String myFileName = fileItem.getName();
System.out.println(myFileName);
// 如果名稱不為“”,說明該檔案存在,否則說明該檔案不存在
if (myFileName!=null&&myFileName.trim() != "") {
//System.out.println(myFileName);
String fileType = myFileName.substring(myFileName
.indexOf(".") + 1);
String saveFileName=DateUtil.getFileName()+fileNum + "."
+ fileType;
if (fileNum % 2 == 1) {// 前面的附件
System.out.println("檔案1大小:"+BigDecimal.valueOf(fileItem.getSize()));
System.out.println("檔案1名稱:"+saveFileName);
} else {
System.out.println("檔案2大小:"+BigDecimal.valueOf(fileItem.getSize()));
System.out.println("檔案2名稱:"+saveFileName);
}
// 定義上傳路徑
String path = curpath + filepath + myFileName;
File localFile = new File(path);
try {
fileItem.write(localFile);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
++fileNum;
}
}
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return this.toshow(request);
}
檔案上傳,下載下傳整個項目源碼。