文件上传
导包
需要导入文件上传的两个jar包
index.jsp
注意使用文件上传的时候,需要将enctype更改为文件上传的编码
springmvc配置文件上传
注意:id不能变
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="51200000"></property> </bean> |
controller
在controller中定义方法,获得上传的文件,并上传到tomcat服务器上
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) { String filename = file.getOriginalFilename(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS"); String format = simpleDateFormat.format(new Date()); filename = format + filename; String path = request.getServletContext().getRealPath("/upload"); File file2 = new File(path); if(!file2.exists()){ file2.mkdir(); } System.out.println(filename); try { file.transferTo(new File(path, filename)); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } |
上传测试
在后台打印上传的图片的名称
在tomcat中找到上传的图片
在浏览器上访问一下该图片