• SSM项目整合 文件上传


    SSM项目整合 文件上传

    一、接口文档

    1.1 图片上传接口

    接口地址: http://localhost:8080/ssm-web/course/courseUpload

    请求方式: POST

    接口描述: 课程模块图片上传

    请求参数:

    file=1597112871741.JPG
    
    • 1

    响应参数:

    参数名称参数说明类型schema
    successboolean
    stateinteger(int32)integer(int32)
    messagestring
    contentobject

    响应示例:

    {
        "success": true,
        "state": 200,
        "message": "响应成功",
        "content": {
            "fileName": "1597112871741.JPG",
            "filePath": "http://localhost:8080/upload/1597112871741.JPG"
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    二、实现过程

    2.1 上传图片功能介绍

    真实开发中 上传图片的位置应该使用独立的服务器,这个服务器只用来上传或者下载图片。以后会学习这个技术(对象存储)

    现在我们选择将图片上传到我们的后端服务器中,我们设计了一个目录为upload专门用来接收上传的图片

    2.2 导包

    <?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.bjpowernode</groupId>
      <artifactId>edu-boss</artifactId>
      <version>1.0</version>
      <packaging>war</packaging>
    
      <name>edu-boss Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com
    
      <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>5.2.0.RELEASE</spring.version>
      </properties>
    
      <dependencies>
        ...
    
        <!-- 文件上传 -->
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
        </dependency>
    
      </dependencies>
    </project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    2.3 SpringMVC的配置文件中配置文件上传解析器

    <?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包-->
        <context:component-scan base-package="com.bjpowernode.edu.controller"/>
        <!--    开启注解驱动-->
        <mvc:annotation-driven/>
    
        <!--配置文件上传解析器-->
        <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
            <!--设置上传文件的最大的大小-->
    <!--        <property name="maxUploadSize" value="10485760"/>-->
            <property name="maxUploadSize" value="#{10*1024*1024}"/>
        </bean>
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2.4 完成文件上传

    CourseController中的代码

     /**
         * 课程图片的上传
         *
         * @param file
         * @return
         */
        @PostMapping("/courseUpload")
        public AjaxResult courseUpload(MultipartFile file, HttpServletRequest request) {
            /*
             *将上传的内容写入upload目录
             * 在upload目录中根据上传图片的日期进行分类
             * 比如今天2022年11月21日 则我们up创建load/2022/10/28目录 将图片上传到这个目录中
             * 文件的名称为了保证不重复 将上传到 文件名称设置为随机数
             */
            String uploadPath = request.getServletContext().getRealPath("/");
            uploadPath = uploadPath.substring(0, uploadPath.indexOf("\\target"));
            //获取upload所在包的绝对路径
            uploadPath += "/src/main/webapp/upload";
    
            //获取当前的年月日 作为upload目录的子目录的名称
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int date = calendar.get(Calendar.DATE);
    
            //上传文件的名称,就是随机数
            String fileName = UUID.randomUUID().toString();
            //获取上传文件的真实的后缀名  作为上传后的文件的后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    
            //将自定义的子目录创建出来
            File f = new File(uploadPath, year + "/" + month + "/" + date);
            f.mkdirs();
    
            //上传图片的最终路径
            File targetFile = new File(uploadPath, year + "/" + month + "/" + date + "/" + fileName + suffix);
            
            //
            try {
                file.transferTo(targetFile);
                Map<String, Object> map = new HashMap<>();
                map.put("filename", fileName + suffix);
                map.put("filepath", "http://localhost:8080/upload/" + year + "/" + month + "/" + date + "/" + fileName + suffix);
                return AjaxResult.success(map);
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.fail("上传失败");
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    三、测试过程

    部署Tomcat
    基本部署省略

    Postman中进行测试
    选择Body
    选择form-data
    选择file
    点击Select Files 选择要上传的文件
    在这里插入图片描述

    点击Send发送请求
    在这里插入图片描述
    如果想让用户通过后端返回的JSON数据的content里面的filepath来访问图片
    那么需要在Tomcat中进行部署配置

    点击“+”->点击External Source
    在这里插入图片描述
    选择upload文件夹
    在这里插入图片描述
    不需要修改路径
    在这里插入图片描述
    重启Tomcat服务器

    再次测试
    在这里插入图片描述
    在浏览器中就可以成功访问了
    在这里插入图片描述

  • 相关阅读:
    WebSocket
    MAUI Android 关联文件类型
    树结构的讲解与二叉树的基本运用
    数据结构——树&二叉树
    信号量Semaphore详解
    Vue 之 Toast 消息提示插件的简单封装
    Azure Terraform(十四)Azure Key Vault 的机密管理
    学习记忆——英语篇
    线程间通信(生产者和消费者案例)
    【MySQL】数据库服务器硬件优化与实战详解(调优篇)(实战篇)(MySQL专栏启动)
  • 原文地址:https://blog.csdn.net/weixin_46411355/article/details/127960667