SpirngBoot上传图片的两种方式——本地——OSS对象存储

Spring Boot实现文件上传功能

在这里插入图片描述

1. 文件上传到本地

适用于单机项目;

  • Spring Boot工程嵌入的tomcat限制了请求的文件大小,每个文件的配置最大为1Mb,单次请求的文件的总数不能大于10Mb。
  • 要更改这个默认值需要在配置文件(如application.properties)中加入两个配置

1.1 核心配置文件application.properties

#单个文件的大小最大为10MB
spring.servlet.multipart.max-file-size=10MB
#单次请求所有文件的大小最大为10MB
spring.servlet.multipart.max-request-size=10MB

#tomcat运行所在的目录。 上传的文件可以直接http://localhost:8080/a.jpg  访问
spring.web.resources.static-locations=classpath:/static/images

1.2 文件上传控制层FileController

package com.guo.springboot.controller;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
public class FileController {

    private static final String UPLOADED_FOLDER = System.getProperty("user.dir")+"/upload";

    @PostMapping("/upload")
    public String upload(MultipartFile file){
        if (file.isEmpty()){
            return "图片上传失败!";
        }
        System.out.println("文件大小:" + (file.getSize()/1024) + "KB");
        String originalFilename = file.getOriginalFilename();
        String ext = "."+originalFilename.split("\\.")[1];  //获取文件的后缀.jpg
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = uuid + ext;
        //获取文件存放位置的绝对路径
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                "\\src\\main\\resources\\static\\images\\";
        String path = pre + fileName;
        return saveFile(file, path);
    }

    private String saveFile(MultipartFile file, String path) {
        try {
            //判断存储的目录是否存在,如果不存在则创建
            File dir = new File(path);
            if (!dir.exists()){
                dir.mkdirs(); //创建多级目录
            }
            System.out.println("上传文件存储的绝对路径:" + path);
            file.transferTo(new File(path));  //把网络中上传的文件存储到路径当中
            return path;
        }catch (Exception e){
            System.out.println("上传失败!出现异常!!!" + e);
            return "上传失败,出现异常!";
        }
    }
}

1.3 用postman测试上传照片

1.3.1 postman发起请求

在这里插入图片描述

1.3.2 程序控制台打印输出
文件大小:784KB
上传文件存储的绝对路径:D:\SpringBoot\git\day1\05-springboot-file\src\main\resources\static\images\0115b949e6cb4b9bb7c97997cdb3faf3.png
1.3.3 根据打印的动态地址去本地磁盘查询

在这里插入图片描述

1.3.4 通过浏览器访问路径去查看

在这里插入图片描述

2. OSS对象存储

适用于分布式 ,

阿里云对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。多种存储类型供选择,全面优化存储成本。

2.1 引入相关依赖

<!--OSS对象存储相关依赖-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.0</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>

2.2 创建工具类

UploadUtil.java

package com.guo.springboot.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

public class UploadUtil {
    //阿里域名
    public static final String ALI_DOMAIN = "https://grh-test.oss-cn-hangzhou.aliyuncs.com/";

    public static String uploadImage(MultipartFile file) throws IOException {
        //生成文件名
        String originalFilename = file.getOriginalFilename(); //原来的图片名
        String ext = "." + FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;
        //地域节点
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

        String accessKeyId = "LTAI5tA******iQL****"; //登录阿里云右上角头像点击后进入AccessKey 管理可以查询到
        String accessKeySecret = "Z1qx6KH9dT*******niS***1I";
        //OSS客户端对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(
                "grh-test", //仓库名
                fileName, //文件名
                file.getInputStream()
        );
        ossClient.shutdown();
        return ALI_DOMAIN + fileName;
    }
}

2.3 控制层

FileController.java


@PostMapping("/uploadOSS")
public String uploadOSS(MultipartFile file){
    try {
        return uploadImage(file);
    } catch (IOException e) {
        System.out.println("异常!" + e);
    }
    return "异常!";
}

2.4 Postman测试

2.4.1 测试上传接口

在这里插入图片描述

2.4.2 通过接口返回的地址去访问,可以下载读取图片

在这里插入图片描述

2.5 去阿里云OSS对象存储管理界面查询统计信息

在这里插入图片描述

SpringBoot可以通过整合阿里云OSS对象存储服务来实现文件上传和管理功能。具体实现可以参考以下步骤: 1. 在service层定义FileService接口,该接口包含上传文件到阿里云OSS的方法。例如,可以使用MultipartFile作为参数,返回上传成功后的文件URL。 2. 在controller层编写FileApiController类,该类使用@RestController注解标识为控制器,并使用@RequestMapping注解指定请求路径。在该类中,通过@Autowired注入FileService,并在文件上传的接口方法中调用FileService的上传文件方法并返回上传成功后的文件URL。 3. 在配置文件中配置阿里云OSS的相关信息,包括accessKey、secretKey、bucketName等。可以使用SpringBoot提供的@ConfigurationProperties注解来读取配置文件中的信息。 4. 在pom.xml文件中添加阿里云OSS SDK的依赖。 5. 编写上传文件的前端界面,可以使用HTML或者前端框架如Vue.js、React等。 通过以上步骤的实现,SpringBoot就可以整合阿里云OSS对象存储服务,实现文件上传和管理功能。这样可以将文件存储在阿里云OSS中,提高文件的安全性和可靠性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合阿里云OSS对象存储服务的实现](https://download.csdn.net/download/weixin_38649091/12721580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [全网最详细SpringBootSpringCloud整合阿里云OSS对象存储服务](https://blog.csdn.net/weixin_55076626/article/details/127924003)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

848698119

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值