程序员、编程、软件开发
面试官:说下spring上传文件MultipartFile
程序汪:单词叫什么,没听过哦
面试官:可以回家等消息了
万能的spring框架什么工具都有
今天要复习的是上传API MultipartFile
org.springframework.web.multipart.MultipartFile
org.springframework.web.multipart.MultipartHttpServletRequest
上传excel文件后端解析进行相应逻辑处理,这是非常平常的需求
@RequestMapping(value = "/uploadFile.json", method = {RequestMethod.GET, RequestMethod.POST})
public ModelMap uploadFile(HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
@RequestParam("file") MultipartFile file) throws IOException {
// TODO 验证(文件类型、大小)
// TODO 解析
// TODO 封装参数返回前端
//TODO finally 里面关闭资源、日志
modelMap.addAttribute(ResultConstants.DATA, resultVO);
return modelMap;
}
MultipartHttpServletRequest
最终也是获取到 MultipartFile
/**
* 文件上传请求
* @return
*/
@RequestMapping(value = "/fileUpload.json", method = { RequestMethod.GET,
RequestMethod.POST })
public void fileUpload(MultipartHttpServletRequest request, HttpServletResponse response,
String classification) throws IOException {
Map
final long startTime = System.currentTimeMillis();
MultipartFile file = request.getFile(“file”);
//获取输入流
InputStream fileStream = file.getInputStream();
//文件名
String fileName = file.getOriginalFilename();
//后缀
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
// TODO 验证(文件类型、大小)
// TODO 解析
// TODO 封装参数返回前端
//TODO finally 里面关闭资源、日志
}
1
文件格式验证,如只支持 XLS|XLSX
String suffix = file.getOriginalFilename()
.substring(file.getOriginalFilename().lastIndexOf(SUFFIX_SPLIT_CHAR) + 1);
用suffix 去匹配 XLS
文件大小验证,必须验证防止后端Full GC
//限制上传文件5M内
if (file.getSize() > MAX_FILE_SIZE) {
//TODO 异常
}
1
org.springframework.web.multipart.MultipartFile
org.springframework.web.multipart.MultipartHttpServletRequest
页面更新:2024-06-03
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号