一次选择多个图片进行上传这是html5有的或者可以利用jq的控件也可以。我采用了html5来写的。由于spring采用name绑定,所以文件的name命名需要注意。下面有前端 controller 以及mybatis的xml
前端页面注意enctype=”multipart/form-data”
name=”graphTheories” multiple
前端
<form action="${pageContext.request.contextPath}/graphTheory/insertPicPath.action" method="post" enctype="multipart/form-data">
<input class="filePrew" tabIndex="3" type="file" size="3" name="graphTheories" multiple>
controller层注意获取参数
public String insertPicPath(HttpSession session,@RequestParam MultipartFile[] graphTheories, HttpServletRequest request) throws Exception {
List<String>newFileNames=UploadFileUtils.uploadFileList(graphTheories, request);
List<GraphTheory>graphTheoryList=new ArrayList<>();
for (String newFileName:newFileNames){
GraphTheory graphTheory=new GraphTheory();
graphTheory.setGraphTheoryImagePicPath(newFileName);
graphTheory.setUserName((String)session.getAttribute("userName"));
graphTheoryList.add(graphTheory);
}
graphTheoryService.insertPicPath(graphTheoryList);
return "success";
}
文件的写入
/**
* 批量上传文件 返回值为文件的新名字 UUID.randomUUID()+originalFilename
* @param multipartFiles
* @param request
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static List<String> uploadFileList(MultipartFile multipartFiles[], HttpServletRequest request) throws IllegalStateException, IOException, CustomException {
List<String>newFileNames=new ArrayList<>();
try {
for(MultipartFile multipartFile:multipartFiles){
//文件的原始名称
String originalFilename=multipartFile.getOriginalFilename();
String newFileName=null;
if (multipartFile!=null&&originalFilename!=null&&originalFilename.length()>0){
newFileName= UUID.randomUUID()+originalFilename;
//存储图片的物理路径
String pic_path = request.getSession().getServletContext().getRealPath("/upload/callRing");
//新图片路径
File targetFile = new File(pic_path, newFileName);
//内存数据读入磁盘
multipartFile.transferTo(targetFile);
newFileNames.add(newFileName);
}
}
}
catch (IOException e){
logger.debug(e.getMessage());
throw new CustomException(e.getMessage());
}
return newFileNames;
}
接下来就是注意下存储到数据库时候的处理,我中间利用redis进行了缓存就不贴出了,这样代码太多不方便查看
<insert id="insertPicPath" parameterType="com.self.po.GraphTheory">
INSERT INTO GraphTheory (graphTheoryImagePicPath,userName) VALUES
<if test="graphTheoryList !=null">
<foreach collection="graphTheoryList" item="graphTheory" separator=",">
(#{graphTheory.graphTheoryImagePicPath},#{graphTheory.userName})
</foreach>
</if>
</insert>