spring+layui实现文件上传
项目背景
前端使用的是layui的方式传过来的form-date数据。当时想做的是可以前端传一个路径,上传的路径保存在这个里面
<div class="upload_btn">上传文件</div>
layui.use('upload', function() {
var upload = layui.upload;
upload.render({
elem: '.upload_btn',
url: 'http://' + _RestPath + '/MMBS_SX/resources/resource/management/springUpload2',
accept: 'file',
multiple: true,
size: 5 * 1024,
data: {
filePath: function() {
return $('.folder_navigation a:last-child').attr('data-path');
}
},
done: function(res) {
loadFileList($('.folder_navigation a:last-child').attr('data-path'));
}
});
})
- 后端代码
@RequestMapping(value = "springUpload2", method = RequestMethod.POST)
public String doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory f = new DiskFileItemFactory();// 磁盘对象
String filePath = "";
f.setRepository(new File("F://temp")); // 设置临时目录
f.setSizeThreshold(1024 * 8); // 8k的缓冲区,文件大于8K则保存到临时目录
ServletFileUpload upload = new ServletFileUpload(f);// 声明解析request的对象
upload.setHeaderEncoding("UTF-8"); // 处理文件名中文
upload.setFileSizeMax(1024 * 1024 * 5);// 设置每个文件最大为5M
upload.setSizeMax(1024 * 1024 * 10);// 一共最多能上传10M
String path = PropertiesConfig.readData("docPath");// 获取文件要保存的目录
String ss = "";
InputStream inputStream = null;
try {
List<FileItem> list = upload.parseRequest(request);// 解析
for (FileItem ff : list) {
if (ff.isFormField()) {
String ds = ff.
getString("UTF-8");// 处理中文
System.err.println("说明是:" + ds);
filePath = ds;
} else {
ss = ff.getName();
ss = ss.substring(ss.lastIndexOf("\\") + 1);// 解析文件名
inputStream = ff.getInputStream();
}
}
if (StringUtils.contains(filePath, path)) {// 因为我设置一个根目 录,判断传过来的文件路径是否包含根目录
path = filePath;
}else {
path+=filePath;
}
FileUtils.copyInputStreamToFile( // 直接使用commons.io.FileUtils
inputStream, new File(path + "/" + ss));
} catch (Exception e) {
return "false";
}
return "true";
}