SpringMVC18_文件上传6

一、文件上传客户端三要素

 文件上传客户端表单需要满足:

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

 webapp/upload.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/quick25" method="post" enctype="multipart/form-data">
        名称<input type="text" name="username"><br/>
        文件<input type="file" name="uploadFile"><br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

  浏览器访问http://localhost:8080/upload.jsp,检查浏览器展示,输入名称,点击“选择文件”弹窗去选择文件

        

二、文件上传原理

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

 

三、单文件上传的代码实现1

 单文件上传步骤:

  1. 导入fileupload和io坐标

  2. 配置文件上传解析器

  3. 编写文件上传代码

  代码实现:

  1. pom.xml导入fileupload和io坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>itheima_spring_mvc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.22.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.22.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.22.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.22.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.14.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>

</project>

  2. spring-mvc.xml配置文件上传解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">



    <!--Controller的组件扫描-->
    <!--如果配置com.itheima则和spring扫重复了-->
    <context:component-scan base-package="com.itheima.controller"/>

    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- /jsp/success.jsp -->
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- mvc的注解驱动 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
   
    <!-- springmvc框架帮你匹配地址,找不到资源,交给原始容器tomcat找静态资源-->
    <mvc:default-servlet-handler />

    <!--  声明转换器  -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.itheima.converter.DateConverter"/>
            </list>
        </property>
    </bean>

    <!--  配置文件上传解析器  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件的编码类型-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件总大小-->
        <property name="maxUploadSize" value="500000"/>
        <!-- 上传单个文件的大小-->
        <property name="maxUploadSizePerFile" value="500000"/>
    </bean>

</beans>

  3. 编写文件上传代码

package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value="/quick25")
    @ResponseBody
    public void save25(String username, MultipartFile uploadFile){
        System.out.println(username);
        System.out.println(uploadFile);
    }
}

  浏览器访问http://localhost:8080/upload.jsp,输入数据提交,检查控制台展示,uploadFile输出了说明文件上传成功了。

       

四、文件上传-单文件上传的代码实现2

  完成文件上传

package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value="/quick25")
    @ResponseBody
    public void save25(String username, MultipartFile uploadFile) throws IOException {
        System.out.println(username);
        System.out.println(uploadFile);
        //获得上传文件的名称
        String originalFilename = uploadFile.getOriginalFilename();
        //将上传的文件转移到/Users/alsc/Desktop/upload/目录下
        uploadFile.transferTo(new File("/Users/alsc/Desktop/upload/"+originalFilename));
    }
}

  浏览器访问http://localhost:8080/upload.jsp,输入数据提交,检查文件上传到了/Users/alsc/Desktop/upload/目录下。

  

五、文件上传-多文件上传的代码实现

 多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改为MultipartFile[]即可。

 实现1:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/quick26" method="post" enctype="multipart/form-data">
        名称<input type="text" name="username"><br/>
        文件1<input type="file" name="uploadFile"><br/>
        文件2<input type="file" name="uploadFile2"><br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>
package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value="/quick26")
    @ResponseBody
    public void save25(String username, MultipartFile uploadFile, MultipartFile uploadFile2) throws IOException {
        System.out.println(username);
        //获得上传文件的名称
        String originalFilename = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("/Users/alsc/Desktop/upload/"+originalFilename));
        String originalFilename2 = uploadFile2.getOriginalFilename();
        uploadFile.transferTo(new File("/Users/alsc/Desktop/upload/"+originalFilename2));
    }
}

 实现2:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/quick27" method="post" enctype="multipart/form-data">
        名称<input type="text" name="username"><br/>
        文件1<input type="file" name="uploadFile"><br/>
        文件2<input type="file" name="uploadFile"><br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>
package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value="/quick27")
    @ResponseBody
    public void save27(String username, MultipartFile[] uploadFile) throws IOException {
        System.out.println(username);
        //获得上传文件的名称
        for (MultipartFile multipartFile:uploadFile) {
            String originalFilename = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("/Users/alsc/Desktop/upload/"+originalFilename));
        }
    }
}

  浏览器访问http://localhost:8080/upload.jsp,输入数据提交,检查两个文件都上传到了/Users/alsc/Desktop/upload/目录下。  

  

六、知识要点

 1. MVC实现数据请求方式

  • 基本类型参数
  • POJO类型参数
  • 数组类型参数
  • 集合类型参数

 2. MVC获取数据细节

  • 中文乱码问题
  • @RequestParam 和 @PathVariable
  • 自定义类型转换器
  • 获得Servlet相关API
  • @RequestHeader 和 @CookieValue
  • 文件上传

 

posted on 2023-05-11 19:49  花溪月影  阅读(29)  评论(0编辑  收藏  举报