springboot 文件和表单一起提交multipart/form
最近用form实现文件上传采用enctype="multipart/form-data方式,后端用springboot
遇到的问题如下:
1.不需要配置什么额外解析器multipartResolver,CommonsMultipartResolver 不需要配置!(网上有文章说配置的都是用的springmvc ,或者比较老),这玩意 springboot已经内置
2.什么request转换不需要 !ShiroHttpServletRequest,如何转换成MultipartHttpServletRequest 不需要!
前端:
<form:form id="inputForm" modelAttribute="fileTemplet" action="${ctx}/file/save" method="post" class="form-horizontal" enctype="multipart/form-data
<input id="fileTitle" name="fileTitle" value="" htmlEscape="false" maxlength="255" class="form-control required" />
<input id="file" name="file" type="file" maxlength="255" class="form-control required" />
后端:
controller:
@RequestMapping(value = "save")
public String save(HttpServletRequest request, FileTemplet fileTemplet, Model model, RedirectAttributes redirectAttributes ,@RequestParam(name = "file") MultipartFile file)
//input参数可以通过下面2种方式获取
request.getParameter("fileTitle");
fileTemplet.getFileTitle();
//上传文件
String filePath = FileUtils.uploadSingleFile(templetTypePath, file);
下载文件实现:
public static String uploadSingleFile(String pathname, MultipartFile fileList) {
try{
String filename = fileList.getOriginalFilename();
File dir = new File(pathname);
if (!dir.exists()) {
dir.mkdirs();
}
String filepath = pathname + filename;
File serverFile = new File(filepath);
fileList.transferTo(serverFile);
return filepath;
}catch (Exception e) {
e.printStackTrace();
return "";
}
}
赞 (0)