1.JSP頁面部分 引入 jQuery v1.8.3.js和bootstrap.css
//配置項
<script type="text/javascript">
var config = {
support: "image/jpg,image/png,image/bmp,image/jpeg,image/gif", // Valid file formats
form: "demoFiler", // Form ID
dragArea: "dragAndDropFiles", // Upload Area ID
uploadUrl: "${ctx}/upload/fileUpload", // Server side upload url
submitHandler:"submitHandler" //上傳按鈕
}
</script>
//JSP頁面
<form name="demoFiler" id="demoFiler" enctype="multipart/form-data">
<input type="file" name="multiUpload" id="multiUpload" multiple/>
<input type="button" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload"/>
</form>
<div class="progress progress-striped active">
<div style="width: 0.1%;" class="bar"></div>
</div>
2.JS
var path=getContextPath();
var delFileList=[];
$(document).ready(function () {
initMultiUploader(config);
});
function multiUploader(config) {
this.config = config;
this.items = "";
this.all = [] ;
this.allFileLists = [];
var self = this;
multiUploader.prototype._init = function () {
if (window.File &&
window.FileReader &&
window.FileList &&
window.Blob) {
var inputId = $("#" + this.config.form).find("input[type='file']").eq(0).attr("id");
document.getElementById(inputId).addEventListener("change", this._read, false);
document.getElementById(this.config.submitHandler).addEventListener("click", this._submit, false);
} else
console.log("Browser supports failed");
}
multiUploader.prototype._submit = function (e) {
e.stopPropagation();
e.preventDefault();
var index=0;
if (self.allFileLists.length > 0) {
document.getElementById('submitHandler').disabled=true;
fileUpload(self.allFileLists,index);
}
}
multiUploader.prototype._preview = function (data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
var sampleIcon = '<img src='+path+'/js/fileUpload/images/image.png />';
var errorClass = "";
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
sampleIcon = '<img src='+path+'/js/fileUpload/images/unknown.png />';
errorClass = " invalid";
}else{
self.allFileLists.push(this.items[i]);
}
html += '<div class="dfiles' + errorClass + '" rel="' + uId + '"><h5>' + sampleIcon + this.items[i].name + '</h5><div id="' + uId + '" class="delete" οnclick="delImg(this)" style=""><img src='+path+'/js/fileUpload/images/trash.png /></div><div id="' + uId + '" class="progress" style="display:none;"><img src='+path+'/js/fileUpload/images/ajax-loader.gif /></div></div>';
}
}
$("#dragAndDropFiles").append(html);
}
}
multiUploader.prototype._read = function (evt) {
if (evt.target.files) {
self._preview(evt.target.files);
self.all.push(evt.target.files);
} else
console.log("Failed file reading");
}
multiUploader.prototype._validate = function (format) {
var arr = this.config.support.split(",");
return arr.indexOf(format);
}
String.prototype._unique = function () {
return this.replace(/[a-zA-Z]/g, function (c) {
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
this._init();
}
function initMultiUploader() {
new multiUploader(config);
}
function shwoProgress(index,total,loaded) {
var width = Math.round(loaded/total * 100) + "%" ;
$("#percentage").html("正在上傳第個"+(index+1)+"檔案,上傳進度:"+width);
$(".bar").css("width",width);
}
var xhrOnProgress=function(fun) {
xhrOnProgress.onprogress = fun; //綁定監聽
//使用閉包實作監聽綁
return function() {
//通過$.ajaxSettings.xhr();獲得XMLHttpRequest對象
var xhr = $.ajaxSettings.xhr();
//判斷監聽函數是否為函數
if (typeof xhrOnProgress.onprogress !== 'function')
return xhr;
//如果有監聽函數并且xhr對象支援綁定時就把監聽函數綁定上去
if (xhrOnProgress.onprogress && xhr.upload) {
xhr.upload.onprogress = xhrOnProgress.onprogress;
}
return xhr;
}
}
function getContextPath(){
//擷取目前網址,如: http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath=window.document.location.href;
//擷取主機位址之後的目錄,如: uimcardprj/share/meun.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//擷取主機位址,如: http://localhost:8083
var localhostPaht=curWwwPath.substring(0,pos);
//擷取帶"/"的項目名,如:/uimcardprj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
if("/report-web-boss"==projectName || "/sboss"==projectName){
return(localhostPaht+projectName);
}else{
return localhostPaht;
}
}
function fileUpload(allFileLists,index){
var file= allFileLists[index];
if (typeof file != undefined ) {
var data = new FormData();
var ids = file.name._unique();
data.append('file', file);
data.append('index', ids);
$("#percentage").html("正在上傳第個"+(index+1)+"檔案,上傳進度:0%");
$(".bar").css("width", "0%");
$(".dfiles[rel='" + ids + "']").find(".progress").show();
$(".dfiles[rel='" + ids + "']").find(".delete").hide();
$.ajax({
type: "POST",
url: config.uploadUrl,
data: data,
cache: false,
contentType: false,
//async: false,
processData: false,
xhr: xhrOnProgress(function (e) {
shwoProgress(index, e.total, e.loaded);
}),
success: function (response) {
$(".dfiles[rel='" + ids + "']").find(".progress").hide();
if ((index + 1) == allFileLists.length) {
allFileLists.length = 0;
$("#dragAndDropFiles").html("");
$("#percentage").html("上傳完成");
document.getElementById('submitHandler').disabled = false;
} else {
index++;
fileUpload(allFileLists,index);
}
}
});
}
}
function delImg(e){
var ids=$(e).attr("id") ;
$(".dfiles[rel='" + ids + "']").remove();
delFileList.pop(ids);
}
3.JAVA 部分
/*
* 采用file.Transto 來儲存上傳的檔案
*/
@RequestMapping("/fileUpload")
@ResponseBody
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
net.sf.json.JSONObject member = new net.sf.json.JSONObject();
try{
String path="D:/upload/"+new Date().getTime()+file.getOriginalFilename();
File newFile=new File(path);
//通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
file.transferTo(newFile);
//建構series所需參數
member.put("success", "ok"); //對應series.name
}catch (Exception e){
member.put("success", "error"); //對應series.name
}
return member.toString();
}
4.SpringMVC配置部分
<!-- 多部分檔案上傳 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>