HTML5+Spring-MVC实现上传图片本地保存
以下就是具体的代码:
1.在jsp页面中的代码:
<span style="font-size:24px;"><form method="post" action="<%=rootPath%>/complaint" onSubmit="return emptyCheck()" enctype="multipart/form-data"> <div id="container4-2" class="font20" style="background-color:#9fa0a0;margin-top:px;padding-top:0px; text-align:center;border:0px; border-bottom-left-radius:3px;border-bottom-right-radius: 3px; color:#ffffff;"> <div style="margin-top:2px;"></div> <!-- <input type="file" value="上传图片" style="border-width: "/> --> <input type="file" name="file" style="position: absolute;opacity: 0.00"/> </div> </form></span>
2.在Controller中的代码
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //先判断request中是否包涵multipart类型的数据, if(multipartResolver.isMultipart(request)){ //再将request中的数据转化成multipart类型的数据 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator iter = multiRequest.getFileNames(); while(iter.hasNext()){ MultipartFile file = multiRequest.getFile((String)iter.next()); if(file != null){ fileName = file.getOriginalFilename(); String typeString=fileName.substring(fileName.lastIndexOf(".")); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String id = sdf.format(new Date()); nameString=id+typeString; path = "C:\\newtomcat\\webapps\\mobile\\userImg"; localFile = new File(path , nameString); clientComplaint.setPath(localFile.getPath());// //写文件到本地 try { FileUtils.copyInputStreamToFile(file.getInputStream(),new File(path,nameString)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
3.在spring-mvc的配置文件中配置信息:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="209715200" /> <property name="defaultEncoding" value="UTF-8" /> <property name="resolveLazily" value="true" /> <!-- 延迟加载 --> </bean>