欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC文件的上传

程序员文章站 2022-07-10 18:50:18
文件上传1文件上传客户端三要素表单项type=“file”表单的提交方式是post表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

文件上传

1文件上传客户端三要素

  • 表单项type=“file”
  • 表单的提交方式是post
  • 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

        <form action="${pageContext.request.contextPath}/user/quick19" method="post" enctype="multipart/form-data" >
            <input type="text" name="username"><br>
            <input type="file" name="uploadFile"><br>
            <input type="submit" value="提交">
        </form>


2文件上传原理

  • 当form表单修改为多部分表单时,request.getParameter()将失效。
  • enctype=“application/x-www-form-urlencoded”时,form表单的正文内容格式是:key=value&key=value&key=valu
  • 当form表单的enctype取值为Mutilpart/form-data时,请求正文内容就变成多部分形式:
    SpringMVC文件的上传

单文件上传实现

1.导入fileupload和io坐标
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
2.配置文件上传解析器
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      	  <!--上传文件的编码类型-->
        <property name="defaultEncoding" value="UTF-8"></property>
          <!--上传文件总大小-->
        <property name="maxUploadSize" value="500000"></property>
    </bean>
3.编写文件上传代码
    @RequestMapping(value = "/quick19")
    @ResponseBody
    public void save19(String username, MultipartFile uploadFile) throws IOException {
 		System.out.println(username);
 		 //获得上传文件的名称
        String originalFilename = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("D:\\upload\\"+originalFilename));
    }

多文件上传实现

<form action="${pageContext.request.contextPath}/user/quick20" method="post" enctype="multipart/form-data" >
    <input type="text" name="username"><br>
    <input type="file" name="uploadFile"><br>
    <input type="file" name="uploadFile"><br>
    <input type="file" name="uploadFile"><br>
    <input type="submit" value="提交">
</form>

    @RequestMapping(value = "/quick20")
    @ResponseBody
    public void save20(String username, MultipartFile[] uploadFile) throws IOException {
        System.out.println(username);
        for (MultipartFile multipartFile:uploadFile ){
            String originalFilename = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("D:\\upload\\"+originalFilename));
        }
    }

本文地址:https://blog.csdn.net/weixin_46111703/article/details/107682876

相关标签: spring mvc