首先application.yml配置項如下
multipart:
enabled: true
file-size-threshold: 30MB
max-file-size: -1
具體參數(shù)說明如下:
(1) multipart.enabled
開啟分段(multi-part)上傳支持选侨。(默認值: true锐想。)
(2)multipart.file-size-threshold
大于該閾值的文件會寫到磁盤上。這里的值可以使用MB或KB后綴來表明是兆字節(jié)還是千字節(jié)旺订。(默認值: 0。)
(3)multipart.location
上傳文件的中間存放位置超燃。
(4)multipart.max-file-size
最大文件大小区拳。這里的值可以使用MB或KB后綴來表明是兆字節(jié)還是千字節(jié)。(默認值:1MB意乓。-1表示無限制)
(5)multipart.max-request-size
最大請求大小樱调。這里的值可以使用MB或KB后綴來表明是兆字節(jié)還是千字節(jié)。(默認值:10MB届良。)
pom.xml需要加入
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
前端
<form id="edit-profile" class="form-horizontal" action="<%=basePath %>upload/beforeUploadExcel"
method="post" enctype="multipart/form-data"/>
<div class="control-group">
<label class="control-label" for="username">文件</label>
<div class="controls">
<input type="file" name="file" class="input-medium disabled"/>
<p class="help-block"></p>
</div>
</div>
<br />
<div class="form-actions">
<button type="submit" class="btn btn-primary">下一步</button>
<button class="btn">取消</button>
</div>
</form>
controlller
@RequestMapping(value = "/beforeUploadExcel", method = RequestMethod.POST)
public String beforeUploadExcel(MultipartHttpServletRequest multiReq, Map<String, Object> model) {
// 從session中獲取用戶信息
User userLogin = (User) session.getAttribute(SessionKeyConstant.USER_INFO);
// 獲取上傳的文件MultipartFile
MultipartFile uploadFile = multiReq.getFile("file");
String fileNameAll = multiReq.getFile("file").getOriginalFilename();
String fileName = fileNameAll.substring(0, fileNameAll.lastIndexOf("."));
// 獲取上傳文件名的后綴
String fileSuffix = fileNameAll.substring(fileNameAll.lastIndexOf("."));
logger.info("上傳文件全名:" + fileNameAll);
logger.info("上傳文件名:" + fileName);
logger.info("文件后綴名:" + fileSuffix);
// 如果文件為空
if (uploadFile == null) {
model.put(PageCodeEnum.KEY, PageCodeEnum.FILEISNULL);
return "/selectfile";
} else if(!fileNameAll.endsWith("xlsx") && !fileNameAll.endsWith("xls")) {
// 文件格式不對
model.put(PageCodeEnum.KEY, PageCodeEnum.FILEILLEGAL);
return "/selectfile";
} else if(!fileService.hasRightName(fileNameAll, userLogin.getUserid())) {
// 文件名不包含項目名
model.put(PageCodeEnum.KEY, PageCodeEnum.FILENAMEISWRONG);
return "/selectfile";
} else {
// 判斷該用戶是否有映射關系笆凌,如果存在,返回usersheetList
List<UserSheet> userSheetList = uploadService.hasMapping(userLogin.getUserid(), fileName);
session.setAttribute(userLogin.getUserid() + ReturnConstant.USER_SHEET_LIST_LAST, userSheetList);
// 文件保存到本地
File commonFile = fileService.saveExcel(multiReq, userLogin);
// 獲取sheet頁名字
Map<String, List<String>> sheetTitleUpload = ExcelUtil.readSheetTitle(commonFile);
logger.info("用戶上傳的sheetTitleUpload:" + sheetTitleUpload);
session.setAttribute(userLogin.getUserid() + SessionKeyConstant.USER_SHEET_TITLE_UPLOAD, sheetTitleUpload);
return "/selectsheet";
}
}
service:存儲文件到本地
/**
* 把文件保存到 resources目錄下士葫,并返回File對象
* @param multiReq
* @return
*/
public File saveExcel(MultipartHttpServletRequest multiReq, User user) {
String fileNameAll = multiReq.getFile("file").getOriginalFilename();
String fileName = fileNameAll.substring(0, fileNameAll.lastIndexOf("."));
logger.info("上傳文件名為:" + fileName);
String path = FileService.class.getResource("/").getPath().substring(1);
// 創(chuàng)建一個以用戶名為名字的文件夾
File pathFile = new File(path + user.getName());
pathFile.mkdir();
File saveFile = new File(path + user.getName() + "/" + fileNameAll);
ByteArrayInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = (ByteArrayInputStream) multiReq.getFile("file").getInputStream();
// 文件寫到resources目錄下
outputStream = new FileOutputStream(saveFile);
byte[] temp = new byte[1024];
int i = inputStream.read(temp);
while (i != -1) {
outputStream.write(temp, 0, temp.length);
outputStream.flush();
i = inputStream.read(temp);
}
// 存到session
session.setAttribute(user.getUserid() + SessionKeyConstant.FILENAME, fileName);
session.setAttribute(user.getUserid() + SessionKeyConstant.SAVEFILE, saveFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return saveFile;
}
說明:如果沒用spring boot乞而,做文件上傳報錯:[org.springframework.web.multipart.MultipartException: The current request is not a multipart request]
可在spring-mvc.xml中添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>