• 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"; //返回失败视图
      }
     }
    }

  • 相关阅读:
    [NSURL initFileURLWithPath:]: nil string parameter 错误的解决方案
    Parser Error Message: Could not load type 错误原因
    C# DropDownList做友情链接打开新窗口
    前两天去A公司面试,面试管问的题目一下子闷了。很郁闷。重新答题。在这里分享一下
    获取枚举描述信息(Description)
    生成实体层的界面(webForm1.aspx)代码
    java中Filter 技术
    hdu_1332&poj_1102_LCDisplay
    hdu_1997_汉诺塔VII
    hdu_1134_Game of Connections_卡特兰数列
  • 原文地址:https://www.cnblogs.com/cuizhf/p/3549593.html
Copyright © 2020-2023  润新知