今天用了一天時間搞定了多文件上傳。
首先是mui代碼,主要就是img標簽,我這里用的是id聲明主要對應后端數據庫的字段 通過src獲取文件路徑包括相冊選擇和手機拍照
<div class="mui-content-padded">
<h4>葯店證件</h4>
<p>請上傳以下證件,證件越齊全,越快通過審核</p>
</div>
<ul class="mui-table-view mui-grid-view" style="text-align: center;">
<li class="mui-table-view-cell mui-media mui-col-xs-5">
<a href="#">
<img class="mui-media-object" src="images/iconfont-tianjia.png" id="zj-photo1" style="height: 9rem; width: 9rem;">
<div class="mui-media-body" style="font-size: 10px;">營業執照<span style="color: red;">(必填)</span>
</div>
</a>
</li>
<li class="mui-table-view-cell mui-media mui-col-xs-5">
<a href="#">
<img class="mui-media-object" src="images/iconfont-tianjia.png" id="zj-photo2" style="height: 9rem; width: 9rem;">
<div class="mui-media-body" style="font-size: 10px;">葯品經營許可證
</div>
</a>
</li>
<li class="mui-table-view-cell mui-media mui-col-xs-5">
<a href="#">
<img class="mui-media-object" src="images/iconfont-tianjia.png" id="zj-photo3" style="height: 9rem; width: 9rem;">
<div class="mui-media-body" style="font-size: 10px;">食品經營許可證
</div>
</a>
</li>
<li class="mui-table-view-cell mui-media mui-col-xs-5">
<a href="#">
<img class="mui-media-object" src="images/iconfont-tianjia.png" id="zj-photo4" style="height: 9rem; width: 9rem;">
<div class="mui-media-body" style="font-size: 10px;">醫療器械經營許可證
</div>
</a>
</li>
</ul>
<div class="mui-content-padded">
<p style="font-size: 0.7em;"><span style="color: red;">
注</span>:<<醫療機構職業許可證>>僅需在[營業執照]處上傳</p>
</div>
<button class="mui-btn mui-btn-block mui-btn-block bg_color_eb6100 btn-apply" id="apply">提交審核</button>
</div>
然后是js代碼
js端主要就是把圖片通過http請求發送到web服務器 保存數據庫等其他的任務交給web服務器完成
mui.init();
function plusReady() {
//Android返回鍵監聽事件
plus.key.addEventListener('backbutton',function(){
myclose();
},false);
}
if (window.plus) {
plusReady();
} else {
document.addEventListener('plusready', plusReady, false);
}
$id('zj-photo1').addEventListener('tap',function(){
showActionSheet($id('zj-photo1'));
});
$id('zj-photo2').addEventListener('tap',function(){
showActionSheet($id('zj-photo2'));
});
$id('zj-photo3').addEventListener('tap',function(){
showActionSheet($id('zj-photo3'));
});
$id('zj-photo4').addEventListener('tap',function(){
showActionSheet($id('zj-photo4'));
});
//取得舊的圖片路徑
var oldPhoto=$id('zj-photo1').src;
var files=[];
$id('apply').addEventListener('tap',function(){
//初始化文件名數組,點擊之后清除之前保存的文件名
files=[];
var ph1src=$id('zj-photo1').src;
var ph2src=$id('zj-photo2').src;
var ph3src=$id('zj-photo3').src;
var ph4src=$id('zj-photo4').src;
//判斷下是否有新圖片被添加
if(ph1src!=oldPhoto){
upload_img(ph1src);
};
if(ph2src!=oldPhoto){
upload_img(ph2src);
};
if(ph3src!=oldPhoto){
upload_img(ph3src);
};
if(ph4src!=oldPhoto){
upload_img(ph4src);
};
//開始上傳
start_upload();
//獲取圖片地址進行上傳
//打開頁面
//寫入緩存
});
//清除照片函數
$id('eliminate').addEventListener('tap',function(){
var ph1src=$id('zj-photo1').src=oldPhoto;
var ph2src=$id('zj-photo2').src=oldPhoto;
var ph3src=$id('zj-photo3').src=oldPhoto;
var ph4src=$id('zj-photo4').src=oldPhoto;
})
//彈出系統選擇框 選擇拍照或者相冊
function showActionSheet(conf){
var divid = conf.id;
var actionbuttons=[{title:"拍照"},{title:"相冊選取"}];
var actionstyle={title:"選擇照片",cancel:"取消",buttons:actionbuttons};
plus.nativeUI.actionSheet(actionstyle, function(e){
if(e.index==1){
getImage(divid);
}else if(e.index==2){
galleryImg(divid);
}
} );
}
//相機選取照片
function getImage(divid) {
var cmr = plus.camera.getCamera();
cmr.captureImage(function(p) {
//alert(p);//_doc/camera/1467602809090.jpg
plus.io.resolveLocalFileSystemURL(p, function(entry) {
//alert(entry.toLocalURL());//file:///storage/emulated/0/Android/data/io.dcloud...../doc/camera/1467602809090.jpg
//alert(entry.name);//1467602809090.jpg
compressImage(entry.toLocalURL(),entry.name,divid);
}, function(e) {
plus.nativeUI.toast("讀取拍照文件錯誤:" + e.message);
});
}, function(e) {
}, {
filename: "_doc/camera/",
index: 1
});
}
//相冊選取照片
function galleryImg(divid) {
plus.gallery.pick( function(p){
//alert(p);//file:///storage/emulated/0/DCIM/Camera/IMG_20160704_112620.jpg
plus.io.resolveLocalFileSystemURL(p, function(entry) {
//alert(entry.toLocalURL());//file:///storage/emulated/0/DCIM/Camera/IMG_20160704_112620.jpg
//alert(entry.name);//IMG_20160704_112620.jpg
//圖片壓縮函數
compressImage(entry.toLocalURL(),entry.name,divid);
}, function(e) {
plus.nativeUI.toast("讀取拍照文件錯誤:" + e.message);
});
}, function ( e ) {
}, {
filename: "_doc/camera/",
filter:"image"
} );
}
//圖片壓縮函數
function compressImage(url,filename,divid){
var name="_doc/upload/"+divid+"-"+filename;//_doc/upload/F_ZDDZZ-1467602809090.jpg
plus.zip.compressImage({
src:url,//src: (String 類型 )壓縮轉換原始圖片的路徑
dst:name,//壓縮轉換目標圖片的路徑
quality:20,//quality: (Number 類型 )壓縮圖片的質量.取值范圍為1-100
overwrite:true//overwrite: (Boolean 類型 )覆蓋生成新文件
},
function(event) {
//uploadf(event.target,divid);
var path = name;//壓縮轉換目標圖片的路徑
//event.target獲取壓縮轉換后的圖片url路
//filename圖片名稱
saveimage(event.target,divid,filename,path);
},function(error) {
plus.nativeUI.toast("壓縮圖片失敗,請稍候再試");
});
}
//圖片保存到本地函數
function saveimage(url,divid,name,path){
//alert(url);//file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg
//alert(path);//_doc/upload/F_ZDDZZ-1467602809090.jpg
var state=0;
var wt = plus.nativeUI.showWaiting();
// plus.storage.clear();
name=name.substring(0,name.indexOf("."));//圖片名稱:1467602809090
var id = document.getElementById("ckjl.id").value;
var itemname=id+"img-"+divid;//429img-F_ZDDZ
var itemvalue=plus.storage.getItem(itemname);
if(itemvalue==null){
itemvalue="{"+name+","+path+","+url+"}";//{IMG_20160704_112614,_doc/upload/F_ZDDZZ-IMG_20160704_112614.jpg,file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg}
}else{
itemvalue=itemvalue+"{"+name+","+path+","+url+"}";
}
plus.storage.setItem(itemname, itemvalue);
// var src = 'src="'+url+'"';
var src =url;
// alert("itemvalue="+itemvalue);
showImgDetail(name,divid,id,src);
wt.close();
}
//將圖片在本地顯示出來
function showImgDetail (imgId,imgkey,id,src) {
document.getElementById(imgkey).src=src;
}
//初始上傳地址
var server="http://192.168.2.202:8080/drug_source/uploadImage.action";
var index=1;
//上傳圖片文件放入數組
function upload_img(p){
//主要是因為MUI 5+ 不支持文件上傳的Key是同一個名字
var n=p.substr(p.lastIndexOf('/')+1);
files.push({name:"uploadkey_" + index,path:p});
index++;
}
//開始上傳
function start_upload(){
//判斷下是否有照片在數組中
if(files.length<=0){
plus.nativeUI.alert("沒有添加上傳文件!");
return;
}
//原生的轉圈等待框
var wt=plus.nativeUI.showWaiting();
var task=plus.uploader.createUpload(server,
{method:"POST"},
function(t,status){ //上傳完成
alert(status);
if(status==200){
//關閉轉圈等待框
wt.close();
}else{
console.log("上傳失敗:"+status);
//關閉原生的轉圈等待框
wt.close();
}
});
//addData 添加上傳數據
// task.addData("client","");
// task.addData("uid",getUid());
for(var i=0;i<files.length;i++){
var f=files[i];
//addFile 添加上傳文件
task.addFile(f.path,{key:f.name});
}
//執行上傳
task.start();
}
最后就是spring mvc 代碼 我這里是放在了用戶的Contorller 中
組件依賴的jar包
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
spring mvc 中要配置multipartResolver 組件的實現類,用來處理上傳文件圖片等。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="5242880"></property>
</bean>
Contorller 接口中的代碼
@RequestMapping("/uploadImage")
public @ResponseBody
String uploadImage(HttpServletRequest request) throws Exception {
// 復雜類型的request對象
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
// 獲取文件名集合放入迭代器
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
//獲取上傳文件的對象
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = newFileName();
String oldfile = mFile.getOriginalFilename();
String sub = oldfile.substring(oldfile.indexOf('.'),
oldfile.length());
//創建一個新的文件名
String newFile = fileName + sub;
try {
//將上傳的文件寫入數組
byte[] bytes = mFile.getBytes();
// 獲取服務器的絕對路徑
String path = request.getSession().getServletContext()
.getRealPath("/");
//創建流對象
OutputStream out = new FileOutputStream(new File(path
+ "/upload/" + newFile));
//將數組寫入到服務器
out.write(bytes);
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
// 生成新文件名
public static String newFileName() {
//時間戳+隨機的三位數
String str = String.valueOf(System.currentTimeMillis())
+ String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
return str;
}