参考官方文件上传代码,js中增加一个before处理参数问题。
参考示例地址: https://www.layui.com/demo/upload.html
参考文档地址: https://www.layui.com/doc/modules/upload.html
html:
<div class="layui-tab-item">
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="fileList">选择多文件</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="fileListAction">开始上传</button>
</div>
<table class="layui-table" id="test" lay-filter="test"></table>
</div>
在upload中增加一个before,在before中添加参数
before: function (obj) {
this.data = {
"BUSINESS_ID": getUrlParam("id"),
"FLOW_ID": getUrlParam("flowId"),
"FLOW_NODE_ID": getUrlParam("flowNodeID")
}///携带额外的数据
}
以下为完整JS
layui.config({
base: '../../../layuiadmin/' //静态资源所在路径
}).extend({
index: 'lib/index' //主入口模块
}).use(['index', 'form', 'layer', 'table', 'upload',], function () {
var form = layui.form
, $ = layui.jquery //由于layer弹层依赖jQuery,所以可以直接得到
, table = layui.table
, upload = layui.upload
, router = layui.router();
var Param = new Object();
//多文件列表示例
var demoListView = $('#demoList')
, uploadListIns = upload.render({
elem: '#fileList'
, size: 102400 //限制文件大小,单位 KB
, exts: 'zip|rar|7z|doc|docx|pdf|txt|xls|ppt|xlsx|pptx|img|jpg|png|gif|bmp|jpeg' //只允许上传压缩文件
, url: webroot + "/guarantee/upload/uploadFile?userid=123456"
, accept: 'file'
, multiple: true
, auto: false
, bindAction: '#fileListAction'
// , data: JSON.stringify(Param)
, 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);
});
}
, before: function (obj) {
this.data = {
"BUSINESS_ID": getUrlParam("id"),
"FLOW_ID": getUrlParam("flowId"),
"FLOW_NODE_ID": getUrlParam("flowNodeID")
}///携带额外的数据
}
, done: function (res, index, upload) {
if (res.code == 0) { //上传成功
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'); //显示重传
}
})
;
//文件列表
table.render({
elem: '#test'
, url: '/file/getAll'
, cellMinWidth: 200
, cols: [[
{field: 'id', width: '5%', title: 'ID', sort: true}
, {field: 'name', width: '20%', title: '文件名'}
, {field: 'host', width: '20%', title: 'Host'}
, {field: 'path', width: '35%', title: '路径', sort: true}
, {field: 'operating', width: '20%', title: '操作'}
]]
});
table.on('radio(test)', function (obj) {
tableCheck = obj.data;
});
//监听事件
table.on('tool(test)', function (obj) {
var data = obj.data; //获得当前行数据
var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
var tr = obj.tr; //获得当前行 tr 的DOM对象
if (layEvent === 'detail') { //查看
//do somehing
} else if (layEvent === 'delete') { //删除
layer.confirm('真的删除行么', function (index) {
obj.del(); //删除对应行(tr)的DOM结构,并更新缓存
layer.close(index);
//向服务端发送删除指令
});
} else if (layEvent === 'update') { //编辑
//do something
//同步更新缓存对应的值
obj.update({
username: '123'
, title: 'xxx'
});
}
});
//监听行单击事件
table.on('row(test)', function (obj) {
//console.log(obj.tr) //得到当前行元素对象
//console.log(obj.data) //得到当前行数据
//obj.del(); //删除当前行
//obj.update(fields) //修改当前行数据
});
//监听行双击事件
table.on('rowDouble(test)', function (obj) {
//obj 同上
//layer.msg(obj.data.host+'/'+obj.data.path);
var index = obj.data.path.lastIndexOf(".");
//获取后缀
var ext = obj.data.path.substr(index + 1);
var isImg = isAssetTypeAnImage(ext);
var isDoc = isDocFunc(ext);
var url = "";
//是否是图片
if (isImg) {
url = obj.data.host + '/' + obj.data.path;
} else if (isDoc) {
url = '/doc/preview?path=' + obj.data.host + '/' + obj.data.path
} else {
layer.msg("无法预览");
}
layer.open({
type: 2,
area: ['700px', '450px'],
fixed: false, //不固定
maxmin: true,
content: url
});
});
/**
* 判断文件是否可直接预览
* @param ext
* @returns {boolean}
*/
function isAssetTypeAnImage(ext) {
return [
'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff', 'txt'].indexOf(ext.toLowerCase()) !== -1;
}
/**
* 是否是文档格式
* @param ext
* @returns {boolean}
*/
function isDocFunc(ext) {
return [
'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].indexOf(ext.toLowerCase()) !== -1;
}
});
后台接受参数:
@PostMapping("/uploadFile")
@ResponseBody
public ReturnMessage upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) {
String BUSINESS_ID = request.getParameter("BUSINESS_ID");
String FLOW_ID = request.getParameter("FLOW_ID");
String FLOW_NODE_ID = request.getParameter("FLOW_NODE_ID");
ReturnMessage returnMessage = new ReturnMessage("0", "文件上传成功");
StringBuffer str = new StringBuffer();
for (MultipartFile files : file) {
if (files.isEmpty()) {
return null;
}
String fileName = files.getOriginalFilename();
logger.info("上传文件,文件名:" + fileName + ",文件大小:" + files.getSize());
File dest = new File(filePath + fileName);
try {
files.transferTo(dest);
str.append("文件" + fileName + "上传成功");
String id = UUID.randomUUID().toString().replaceAll("-", "");
String serverid = UUID.randomUUID().toString().replaceAll("-", "") + files.getContentType();
String itemID = request.getAttribute("item_id").toString();
Date uploadTime = new java.sql.Date(System.currentTimeMillis());
String flowNodeID = request.getAttribute("flow_node_id").toString();
String user_id = request.getAttribute("user_id").toString();
String user_name = request.getAttribute("user_name").toString();
GuarItemFile guarItemFile = new GuarItemFile(id, "1", itemID, "项目附件", fileName, "", serverid, serverid + FileUtil.getExtensionName(fileName), uploadTime, flowNodeID, FileUtil.getExtensionName(fileName), user_id, user_name);
guarItemFileService.addGuarItemFile(guarItemFile);
logger.info("文件" + fileName + "上传成功");
} catch (IOException e) {
str.append("文件" + fileName + "上传失败");
logger.info(e.getMessage());
//LOGGER.error(e.toString(), e);
}
returnMessage.setMsg(str.toString());
}
return returnMessage;
}
Comments | NOTHING