问题描述
使用SpringMVC+layui上传文件,layui使用官方给的模板,SpringMVC后端参考博文:layui多文件上传springMVC后端处理
但是跑起来后网页弹窗报错:文件上传接口出错,并且显示重传按钮。打开控制台后发现报错为Completed 406 NOT_ACCEPTABLE,大意是返回的数据类型与前端期望的不一致,如下图所示:
然而打开idea的out文件夹,找到自己写的上传路径,会发现文件已经上传成功:
前端jsp
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
<div class="layui-upload-list" style="max-width: 1000px;">
<table class="layui-table">
<colgroup>
<col>
<col width="150">
<col width="260">
<col width="150">
</colgroup>
<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>
layui.use(['upload', 'element', 'layer'], function () {
var $ = layui.jquery
, upload = layui.upload
, element = layui.element
, layer = layui.layer;
var uploadListIns = upload.render({
elem: '#testList'
, elemList: $('#demoList') //列表元素对象
, url: '${pageContext.request.contextPath}/upload' //此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
, accept: 'file'
, multiple: true
, number: 3
, auto: false
, bindAction: '#testListAction'
, choose: function (obj) {
var that = this;
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><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></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 值,以免删除后出现同名文件不可选
});
that.elemList.append(tr);
element.render('progress'); //渲染新加的进度条组件
});
}
, done: function (res, index, upload) { //成功的回调
var that = this;
//if(res.code == 0){ //上传成功
var tr = that.elemList.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(3).html(''); //清空操作
delete this.files[index]; //删除文件队列已经上传成功的文件
return;
//}
this.error(index, upload);
}
, allDone: function (obj) { //多文件上传完毕后的状态回调
console.log(obj)
}
, error: function (index, upload) { //错误回调
var that = this;
var tr = that.elemList.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
, progress: function (n, elem, e, index) { //注意:index 参数为 layui 2.6.6 新增
element.progress('progress-demo-' + index, n + '%'); //执行进度条。n 即为返回的进度百分比
}
});
})
</script>
后端SpringMVC
@RequestMapping(value = "upload")
@ResponseBody
public JSONObject upload(MultipartFile file, HttpServletRequest req) throws IOException {
/*
* MultipartFile:来源于SpringMVC这个框架,对应页面中的file输入流
*/
//获取到原始的文件名
String fileName = file.getOriginalFilename(); //通过输入流对象,获取文件名,上传的真实文件名
//获取文件的后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
//获取文件除前缀外的名字
String name = fileName.substring(0,fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();//生成一个新的文件名,避免文件同名出现文件覆盖的现象
//如果需要将文件存放在当前的项目中,使用request.getrealpath()
String path = req.getServletContext().getRealPath("/xxx/");
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + "\\" + name + uuid + suffix));
JSONObject jsonobj = new JSONObject();
jsonobj.put("code", 0); //向layui返回成功回调的标记
return jsonobj;
}
原因分析
我的Jackson导入总是出错,所以后来改用fastjson代替Jackson返回json格式,在SpringMVC.xml中的配置如下:
<!--配置fastjson为默认JSON解析器:使用fastjson代替jackjson返回json格式 -->
<!--修改mappingJacksonHttpMessageConverter的 class值为FastJson的MessageConverter就可以了-->
<bean id="mappingJacksonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
</list>
</property>
</bean>
然而fastjson返回json数据时需要将返回值一概写为String类型,比如:
@RequestMapping("xxx")
@ResponseBody //以json格式回传数据
public String ReturnTest(){
List<student> list=new ArrayList<>();
list.add(new student(xxx,xxx,xxx,xxx);
list.add(new student(yyy,yyy,yyy,yyy);
//return list;
return JSON.toJSONString(list);
}
所以后端执行成功后向前端返回JSONObject类型的数据,layui并不将其认为json格式,故报错。而文件上传是执行成功了的,所以服务器端存在上传的文件。
解决方式
将SpringMVC中controller的返回值改为String类型,layui显示接收成功:
后端代码:
@RequestMapping(value = "upload")
@ResponseBody
public String upload(MultipartFile file, HttpServletRequest req) throws IOException {
/*
* MultipartFile:来源于SpringMVC这个框架,对应页面中的file输入流
*/
//获取到原始的文件名
String fileName = file.getOriginalFilename(); //通过输入流对象,获取文件名,上传的真实文件名
//获取文件的后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
//获取文件除前缀外的名字
String name = fileName.substring(0,fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();//生成一个新的文件名,避免文件同名出现文件覆盖的现象
//如果需要将文件存放在当前的项目中,使用request.getrealpath()
String path = req.getServletContext().getRealPath("/xxx/");
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + "\\" + name + uuid + suffix));
JSONObject jsonobj = new JSONObject();
jsonobj.put("code", 0);
return jsonobj.toString();
}