案例14 Spring MVC文件上传案例

基于Spring MVC实现文件上传:

  1. 使用commons-fileupload实现上传文件到本地目录。

  2. 实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。

1. 创建项目

选择Maven快速构建web项目,项目名称为case14-springmvc03。

2. 配置Maven依赖

XML 复制代码
<?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.wfit.springmvc</groupId>
  <artifactId>springmvc02</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <!--spring mvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.8</version>
    </dependency>
    <!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!--fileupload-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <!--aliyun-sdk-oss-->
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.15.1</version>
    </dependency>
  </dependencies>
</project>

3. 创建Spring MVC配置文件

src.main.resources目录下创建spring-mvc.xml。

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">
    <!--开启注解-->
    <context:component-scan base-package="com.wfit"/>
    <!--启用mvc-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置上传大小 最大1M-->
        <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>

4. 配置web.xml

XML 复制代码
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <!--解决POST中文乱码问题 过滤器-->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置前端控制器DispatcherServlet-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载SpringMVC文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <!--启动容器时加载servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--表示拦截所有请求-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

5. 创建UploadController类

在src.main.java.com.wfit.upload目录下创建UploadController类,实现文件上传。

java 复制代码
@Controller
@RequestMapping("/upload")
public class UploadController {
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        //验证文件是否为空
        if(ObjectUtils.isEmpty(file) || file.getSize() <=0){
            return "file is empty";
        }
        //创建上传文件位置
        File uploadDir = new File("D:\\upload");
        //获取文件名
        String fileName = file.getOriginalFilename();
        //创建目标文件
        File desFile = new File(uploadDir,fileName);
        //执行上传操作
        file.transferTo(desFile);
        return "success";
    }
}

6. 创建OssController类

在src.main.java.com.wfit.upload目录下创建OssController类,实现上传文件到阿里云OSS和从阿里云OSS下载文件到本地。

java 复制代码
@Controller
@RequestMapping("/oss")
public class OssController {

    //访问OSS的域名
    private static String endpoint = "oss-cn-beijing.aliyuncs.com";
    //accessKeyId和accessKeySecret是OSS的访问密钥
    private static String accessKeyId = "<yourAccessKeyId>";
    private static String accessKeySecret = "<yourAccessKeySecret>";
    //Bucket用来管理所存储Object的存储空间
    private static String bucketName = "<yourBucketName>";
    //目标文件
    private static String objectName = "upload/123.txt";
    /**
     * 上传文件到阿里云OSS
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        //验证文件是否为空
        if(ObjectUtils.isEmpty(file) || file.getSize() <=0){
            return "file is empty";
        }
        InputStream inputStream = file.getInputStream();
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置,则返回的response为空
            putObjectRequest.setProcess("true");
            // 创建PutObject请求
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功,则返回200
            System.out.println(result.getResponse().getStatusCode());
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } 
        return "success";
    }

    /**
     * 下载阿里云文件到本地
     * @return
     */
    @PostMapping("/download")
    @ResponseBody
    public String download(String objName,String path) throws IOException {
        //下载目录
        String pathName = "download/123.txt";
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 下载Object到本地文件,并保存到指定的本地路径中
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        }
        return "success";
    }
}

7. Postman执行上传文件到本地目录

8. Postman执行上传到阿里云OSS

9. Postman执行从阿里云OSS下载文件到本地

相关推荐
一元咖啡几秒前
SpringCloud Gateway转发请求到同一个服务的不同端口
spring·spring cloud·gateway
儿时可乖了7 分钟前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite
ruleslol8 分钟前
java基础概念37:正则表达式2-爬虫
java
xmh-sxh-131425 分钟前
jdk各个版本介绍
java
天天扭码44 分钟前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶44 分钟前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺1 小时前
Spring Boot框架Starter组件整理
java·spring boot·后端
小曲程序1 小时前
vue3 封装request请求
java·前端·typescript·vue
陈王卜1 小时前
django+boostrap实现发布博客权限控制
java·前端·django
小码的头发丝、1 小时前
Spring Boot 注解
java·spring boot