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";
}