zoukankan      html  css  js  c++  java
  • Spring MVC文件上传

    1.配置xml文件

    1 <!-- 指定文件上传解析  名字不能乱给 -->
    2     <bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    3         <property name="defaultEncoding" value="utf-8" />
    4         <property name="maxUploadSize" value="9223372036854775807" />
    5     </bean>

    2.编写代码

     1     @RequestMapping(value="flatform/app/appinfoaddsave")
     2     public String appinfoaddsave(App_info app_info, MultipartFile a_logoPicPath, Model m, HttpSession session) throws IOException {
     3         if (a_logoPicPath.getSize() > 1024*50) {
     4             m.addAttribute("fileUploadError", "文件大小不能超过50kb!");
     5             return "jsp/developer/appinfoadd";
     6         }
     7         String filename = a_logoPicPath.getOriginalFilename();                                                    //文件名称
     8         String contextPath = session.getServletContext().getContextPath();                                //相对路径
     9         String realPath = session.getServletContext().getRealPath("statics/uploadfiles");            //绝对路径
    10         String type = a_logoPicPath.getContentType();                                                                //文件类型
    11         File file = new File(realPath, filename);
    12         if ("image/png".equals(type) || "image/jpg".equals(type) || "image/jpeg".equals(type)) {
    13             a_logoPicPath.transferTo(file);                                                    //将图片保存到本地
    14             app_info.setLogoLocPath(realPath+"\"+filename);
    15             app_info.setLogoPicPath(contextPath+"/statics/uploadfiles/"+filename);
    16             app_infoService.appinfoaddsave(app_info);
    17             return "redirect:list";
    18         } else {
    19             m.addAttribute("fileUploadError", "文件类型只能是jpg、jpeg、png!");
    20             return "jsp/developer/appinfoadd";
    21         }
    22     }

    最后需要再jsp页面中的form标签中加上 enctype="multipart/form-data"。

    注意:jsp页面中文件控件的name属性和MultipartFile参数名称要相同,否则spring mvc映射不到,文件自然接收不到。

       如果名称实在是不想写成一样的话,可以MultipartFile参数前加@RequestParam("控件的name属性")来映射。

    欢迎提出意见或建议!!!
  • 相关阅读:
    using 关键字在 C++ 中的几种用法
    Chromium 修改图片资源
    SAM&广义SAM
    Burnside和Polya
    笔记:杜教筛
    笔记:莫比乌斯反演
    Miller-Rabin
    点分治
    虚树
    计算几何
  • 原文地址:https://www.cnblogs.com/gaofei-1/p/7436155.html
Copyright © 2011-2022 走看看