html页面代码
直接复制layui官方文档代码
<div class="layui-upload">
<button class="layui-btn layui-btn-normal" id="testList" type="button">选择文件</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 class="layui-btn" id="testListAction" type="button">开始上传</button>
</div>
js代码
直接在官方文档复制的代码的基础上修改
<script>
var files=[];
//JavaScript代码区域
layui.use(['element','upload'], function(){
var $ = layui.jquery
,upload = layui.upload;
//上传
//多文件列表示例
var demoListView = $('#demoList')
,uploadListIns = upload.render({
elem: '#testList'
,url: '/data/uploadSource' //改成您自己的上传接口
,accept: 'file'
,exts: 'txt|rar|zip|doc|docx|pdf|xls|xlsx' //允许上传的文件类型
,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/1024).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){
if (res.code == 0){
files.push({"fileName":res.filename,"fileUrl":res.fileUrl,"fileSize":res.fileSize});//,"fileUrl":res.fileUrl
var json = JSON.stringify(files);
//将上传的文件信息加入到集合中并转换成json字符串
$("#fileJson").attr("value",json);
var fileUrl = res.fileUrl;
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
tds.eq(3).html('<span>'+fileUrl+'</span>');
tds.eq(4).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>
后台controller代码
package com.example.demo1.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author dy
* @version 1.0
* @date 2020/2/27 15:47
*/
@Controller
@RequestMapping(value = "/data")
public class DataController {
@RequestMapping(value="/uploadSource" , method = RequestMethod.POST)
@ResponseBody
public String uploadSource(@RequestParam("file") MultipartFile file) {
System.out.println(file);
String pathString = null;
if(file!=null) {
//获取上传的文件名称
String filename = file.getOriginalFilename();
//文件上传时,chrome与IE/Edge对于originalFilename处理方式不同
//chrome会获取到该文件的直接文件名称,IE/Edge会获取到文件上传时完整路径/文件名
//Check for Unix-style path
int unixSep = filename.lastIndexOf('/');
//Check for Windows-style path
int winSep = filename.lastIndexOf('\\');
//cut off at latest possible point
int pos = (winSep > unixSep ? winSep:unixSep);
if (pos != -1)
filename = filename.substring(pos + 1);
pathString = "E:/upload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;//上传到本地
}
try {
File files=new File(pathString);//在内存中创建File文件映射对象
//打印查看上传路径
System.out.println(pathString);
if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
files.getParentFile().mkdirs();//创建所有父文件夹
}
file.transferTo(files);//采用file.transferTo 来保存上传的文件
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\"}";
}
}
上传成功显示页面
遇到的问题
- 请求上传接口异常 - FileNotFoundException
- org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
- 返回值问题
layui官方代码要求返回的json格式
{
"code": 0
,"msg": ""
,"data": {
"src": "http://cdn.layui.com/123.jpg"
}
}