3.Springmvc的文件上传

来源:互联网 发布:flush软件 编辑:程序博客网 时间:2024/04/28 02:06
1.在SpringMVC的配置文件中配置文件上传的解析器:
  1. <!-- 配置文件上传的解析器,不配置的话参数不能传入 -->
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  3. <property name="maxUploadSize">
  4. <value>5242880</value>
  5. </property>
  6. </bean>

2.文件上传的jsp页面:(post请求,enctype="multipart/form-data")
注:
jsp页面获取项目路径:${pageContext.request.contextPath}
java代码获取项目路径request.getContextPath()
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. ...
  3. <%
  4. pageContext.setAttribute("APP_PATH", request.getContextPath());
  5. %>
  6. </head>
  7. <body>
  8. <form action="${APP_PATH}/user" method="post" enctype="multipart/form-data">
  9. 上传文件:<input type="file" name="file"/>
  10. 提交:<button type="submit"/>
  11. </form>
  12. </body>
  13. ...

3.控制器处理上传文件的请求:
  1. @Controller
  2. public class UserController {
  3. /**
  4. * 上传文件
  5. */
  6. @RequestMapping("/user")
  7. public String getFile(MultipartFile file, Model model) throws Exception{
  8.        //要判断file不为null的情况下...否则可能报空指针异常
  9. //1.设置文件上传路径
  10. String upload_path = "D:\\myDownload\\pictures\\";//最后的"\\"为了加上后缀.xxx
  11. //2.获取文件名
  12. String originalFilename = file.getOriginalFilename();
  13. //3.获取后缀名(.xxx)
  14. String pointName = originalFilename.substring(originalFilename.indexOf("."));
  15. //新名字
  16. String newName = UUID.randomUUID().toString()+pointName;
  17. //4.创建本地文件
  18. File newFile = new File(upload_path+newName);
  19. //5.将内存中的数据写入磁盘
  20. file.transferTo(newFile);
  21. model.addAttribute("model", newName);
  22. return "fileLoad";
  23. }
  24. }

4.跳转到fileLoad.jsp页面,回显图片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. ...
  4. <body>
  5.    <!-- pic是配置的虚拟路径:详情见tomcat虚拟路径的配置 -->
  6.    <!-- /开头代表绝对路径 pic --> D:\myDownload\pictures -->
  7. <img src="/pic/${model }">
  8. </body>
  9. </html>


原创粉丝点击