• 文件上传


    1、基于apache的commons-fileupload.jar 完成文件上传

    2、MultipartResovler作用:

      2.1 把客户端上传的文件流转换成MutipartFile封装类  

      2.2 通过MutipartFile封装类获取到文件流

    3、表单数据类型分类:(method=“post” 最大2GB)   (get是字符流(2KB) post是字节流)

        3.1、在<form> 的enctype是控制表单数据类型的属性

      3.2、默认值 application/x-www-form-urlencoded 普通表单数据(少量文字信息)

      3.3、text/plain 大文字量时使用的类型,邮件,论文

      3.4、multipart/form-data 表单中包含二进制文件内容

    4、实现步骤:

      4.1、导入springmvc包和apache文件上传commons-fileupload和commons-io两个jar

      4.2、编写JSP页面

      <body>
        <form action="upload" enctype="multipart/form-data" method="post">
            姓名:<input type="text" name="name"><br/>
            文件:<input type="file" name="file"></br>
            <input type="submit" value="提交吧">
        </form>
      </body>

      4.3、配置springmvc.xml

            <!-- MultipartResolver解析器 -->
            <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <property name="maxUploadSize" value="50"></property>
            </bean>
            <!-- 异常解析器 -->
            <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
                <property name="exceptionMappings">
                    <props>
                        <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
                    </props>
                </property>
            </bean>

      4.4、编写控制器类

        4.4.1 MultipartFile对象名必须和<input type="file"/>的name属性值相同

    @Controller
    public class DemoController {
        @RequestMapping("upload")
        public String upload(MultipartFile file,String name) throws IOException{
            System.out.println("name"+name);
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            //判断上传文件类型
            if (suffix.equalsIgnoreCase(".png")) {            
                UUID uuid = UUID.randomUUID();
                FileUtils.copyInputStreamToFile(file.getInputStream(),new File("D:/"+uuid+suffix));
                return "/index.jsp";
            }else{
                return "/error.jsp";
            }
        }
    }
  • 相关阅读:
    hdu 1240:Asteroids!(三维BFS搜索)
    hdu 2199:Can you solve this equation?(二分搜索)
    hdu 1195:Open the Lock(暴力BFS广搜)
    【ACM
    hrbustoj 1161:Leyni(树状数组练习)
    时间作为横轴的图表(morris.js)超越昨天的自己系列(8)
    Bean实例化(Spring源码阅读)-我们到底能走多远系列(33)
    Sharded实现学习-我们到底能走多远系列(32)
    初始化IoC容器(Spring源码阅读)-我们到底能走多远系列(31)
    一致性哈希算法 应用场景(转)
  • 原文地址:https://www.cnblogs.com/axu521/p/10169100.html
Copyright © 2020-2023  润新知