springmvc + layui上传组件 + mysql 实现简单上传功能
如果想基于servlet3.0实现的多部分解析器StandardServletMultipartResolver来做上传功能,请参考这个blog:http://blog.csdn.net/just4you/article/details/70233133
下面使用CommonsMultipartResolver解析器实现:
spring mvc中对于多部件解析的配置文件:
<!-- 多部分解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971520"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
jsp页面的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String ctxPath = request.getContextPath();
request.setAttribute("ctxPath", ctxPath);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<title>layui实现上传</title>
<script src="<%=request.getContextPath()%>/js/jquery/jquery-3.2.1.js"
charset="utf-8"></script>
<script src="<%=request.getContextPath()%>/js/layui2.1.5/layui.js"
charset="utf-8"></script>
<link rel="stylesheet"
href="<%=request.getContextPath()%>/js/layui2.1.5/css/layui.css">
<style>
</style>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>高级应用:制作一个多文件列表</legend>
</fieldset>
<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>
<script type="text/javascript">
layui.use('upload', function(){
var $ = layui.jquery,upload = layui.upload;
var url = '<%=request.getContextPath() %>/file/upload';
//多文件列表示例
var demoListView = $('#demoList')
,uploadListIns = upload.render({
elem: '#testList'
,url: url
,accept: 'file'
,multiple: true
,auto: false
,bindAction: '#testListAction'
,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-mini demo-reload layui-hide">重传</button>'
,'<button class="layui-btn layui-btn-mini 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){
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'); //显示重传
}
});
});
</script>
</body>
</html>
controller 代码实现:
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import bugeasy.base.SystemConstant;
import bugeasy.base.bean.FileBean;
import bugeasy.base.service.FileService;
/**
* @author Kevin 2018-1-18
*
* 上传控制器
*
*/
@Controller
@RequestMapping("/file")
public class FileController {
@Autowired
private FileService fileService;
@RequestMapping("/upload")
@ResponseBody
public ModelMap upload(@RequestParam("file") CommonsMultipartFile[] files){
ModelMap m = new ModelMap();
if(files != null){
try {
String path = "";
String fileName = "";
for(CommonsMultipartFile file : files){
fileName = file.getFileItem().getName();
//服务器文件存储地址,根据实际情况变动!
path = SystemConstant.FILE_SERVER_PATH + "\" + fileName ;
/**
* 这里调用spring提供的方法,当然也可以自己读写流(file.getInputStream())等方式去操作
*/
file.transferTo(new File(path));
}
FileBean fileBean = new FileBean();
fileBean.setId(UUID.randomUUID().toString().replace("-", ""));
fileBean.setFileName(fileName);
fileBean.setFilePath(path);
fileBean.setUploadTime(new Date());
fileService.addFile(fileBean);
//layui组件需要code=0判断成功!否则失败
m.put("code", "0");
} catch (IOException e) {
e.printStackTrace();
}
}
return m;
}
}
service和dao层代码实现省略。
启动服务实现效果如下:
注意:layui提供的多文件上传是使用队列一个文件一次请求发送。