zoukankan      html  css  js  c++  java
  • spring mvc 3.0 实现文件上传功能

    http://club.jledu.gov.cn/?uid-5282-action-viewspace-itemid-188672

    ————————————————————————————————————————————————————————

        spring mvc 支持web应用程序的文件上传功能,是由spring内置的即插即用的MultipartResolver来实现的,这些解析器都定义在org.springframework.web.multipart包里。下面将使用CommonsMultipartResolver解析器来实现简单的文件上传功能。

        web应用程序上下文配置文件中(我的配置文件名为 /WEB-INF/config/app-config.xml)定义如下:

     <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <!-- 以字节为单位的最大上传文件的大小 -->
      <property name="maxUploadSize" value="100000" />
     </bean>

        入两个依赖的jar包(spring官网可以下载到对应版本的常用依赖jar包):

        com.springsource.org.apache.commons.io-1.4.0.jar
        com.springsource.org.apache.commons.fileupload-1.2.0.jar

        建一个HTML表单:

     <body>
      <h1>
       Spring MVC 3.0 文件上传测试
      </h1>   //action里的html是后缀名,不是HTML文件,用于spring对请求进行拦截判断
      <form. method="post" action="upload.html" enctype="multipart/form-data">
       <input type="text" name="name" />
       <input type="file" name="file" />
       <input type="submit" />
      </form>
     </body>

        创建一个controller(控制器)来处理文件上传请求,FileUploadController.java:

    @Controller //声明该类为控制器类
    public class FileUploadController implements ServletContextAware{ //实现ServletContextAware接口,获取本地路径

     private ServletContext servletContext;

     public void setServletContext(ServletContext servletContext) { //实现接口中的setServletContext方法
      this.servletContext = servletContext;
     }

     @RequestMapping(value = "/upload", method = RequestMethod.POST) //将文件上传请求映射到该方法
     public String handleFormUpload(@RequestParam("name") String name, //设置请求参数的名称和类型
       @RequestParam("file") CommonsMultipartFile mFile) { //请求参数一定要与form中的参数名对应
      if (!mFile.isEmpty()) {
       String path = this.servletContext.getRealPath("/tmp/");  //获取本地存储路径
       File file = new File(path + new Date().getTime() + ".jpg"); //新建一个文件
       try {
        mFile.getFileItem().write(file); //将上传的文件写入新建的文件中
       } catch (Exception e) {
        e.printStackTrace();
       }
       
       return "redirect:uploadSuccess"; //返回成功视图
      }else {
       return "redirect:uploadFailure"; //返回失败视图
      }
     }
    }

  • 相关阅读:
    MyBatis环境配置
    log4j配置不同的类多个日志文件
    Http协议头、代理
    Apache二级域名实现
    Flash Builder 4.7 完美破解
    网页设计方面,哪些中英文字体的组合能有好的视觉效果
    网页设计中最常用的字体
    sublime text 3 插件:package control
    大量实用工具类、开源包,该帖绝对值得你收藏!
    10个简化Web开发者工作的HTML5开发工具
  • 原文地址:https://www.cnblogs.com/cuizhf/p/3549593.html
Copyright © 2011-2022 走看看