jsp 頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/common/common.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="css/layui.css">
</head>
<body>
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="testList">選擇多文件</button>
<div class="layui-upload-list">
<table class="layui-table">
<thead>
<tr><th>文件名</th>
<th>大小</th>
<th>狀態</th>
<th>操作</th>
</tr></thead>
<tbody id="demoList"></tbody>
</table>
</div>
<button type="button" class="layui-btn" id="testListAction">開始上傳</button>
</div>
</body>
<script type="text/javascript" src="js/layui.js"></script>
<script type="text/javascript" src="js/layui.all.js"></script>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.12.3.js"></script>
<script type="text/javascript">
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//多文件列表示例
var demoListView = $('#demoList')
,uploadListIns = upload.render({
elem: '#testList'
,url: '<%=path%>/Lol_uploadFile.action'
,accept: 'file'
,data:{id:123} //還可以傳參,參數id=123
,multiple: true
,auto: false
,bindAction: '#testListAction'
,success:function(msg) {
$.each($.parseJSON(msg.jsonData),function(i,item){
if (item.fileName==1) {
alert("ok");
} else {
alert("ok");
}
});
}
,choose: function(obj){
var files = this.files = obj.pushFile(); //將每次選擇的文件追加到文件隊列
//讀取本地文件
obj.preview(function(index, file, result){
var tr = $(['<tr id="upload-'+ index +'">'
,'<td>'+ file.name +'</td>'
,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
,'<td>等待上傳</td>'
,'<td>'
,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重傳</button>'
,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">刪除</button>'
,'</td>'
,'</tr>'].join(''));
//單個重傳
tr.find('.demo-reload').on('click', function(){
obj.upload(index, file);
});
//刪除
tr.find('.demo-delete').on('click', function(){
delete files[index]; //刪除對應的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除后出現同名文件不可選
});
demoListView.append(tr);
});
}
,done: function(res, index, upload){
$.each($.parseJSON(res.jsonData),function(i,item){
if(item.success==1) {//上傳成功
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上傳成功</span>');
tds.eq(3).html(''); //清空操作
return delete this.files[index]; //刪除文件隊列已經上傳成功的文件
}
});
this.error(index, upload);
}
,error: function(index, upload){
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('<span style="color: #FF5722;">上傳失敗</span>');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //顯示重傳
}
});
});
</script>
</html>
action方法
需要添加兩個屬性
List<File> file;
List<String> fileFileName;
//記住要添加對應的get、set
public String updateImg() throws Exception {
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
if(UploadFile.uploadFileBase(0, file, fileFileName, UPLOADDIR)) {
BusinessImage bsnImg = new BusinessImage();
bsnImg.setId(Integer.parseInt(imgId));
bsnImg.setImgUrl(UPLOADDIR+"/"+fileFileName.get(0));
businessImageServiceImpI.updateBusinessImageAjax(bsnImg);
obj.put("success", "1");
} else {
obj.put("success", "0");
}
array.put(obj);
jsonData = array.toString();
System.out.println(jsonData);
return SUCCESS;
}
圖片上傳工具類
package com.gxuwz.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
public class UploadFile {
@SuppressWarnings("deprecation")
public static boolean uploadFileBase(int i,List<File> file,List<String> fileFileName,String uploadPath) throws Exception {
try {
InputStream in = new FileInputStream(file.get(i));
String dir = ServletActionContext.getRequest().getRealPath(uploadPath);
File fileLocation = new File(dir);
//此處也可以在應用根目錄手動建立目標上傳目錄
if(!fileLocation.exists()){
boolean isCreated = fileLocation.mkdir();
if(!isCreated) {
//目標上傳目錄創建失敗,可做其他處理,例如拋出自定義異常等,一般應該不會出現這種情況。
return false;
}
}
String fileName=fileFileName.get(i);
File uploadFile = new File(dir, fileName);
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
return true;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return false;
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
}
}
如果不會配struct.xml 請往下看
<package name="data-json" extends="json-default" namespace="/">
<action name="*_*" class="com.gxuwz.Market.business.action.web.{1}Action" method="{2}">
<result name="success" type="json">
<param name="json">jsonData</param>
</result>
</action>
</package>