基于Springboot的方式上传图片到阿里云的OSS存储

     今天做到了上传图片的这个功能,经过在b站以及csdn的摸爬滚打终于学会了,现在在这里记录一下

1.首先需要导入三个依赖

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

2.开始编写工具类  上传图片 uploadImage

package com.example.blog.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 UploadImage {
    //阿里oss的Bucket 域名
    private static final String HTTP = "https://+xxxxx;

    public static  String uploadImage(MultipartFile file) throws IOException {
        //生成新的文件名
        //重新命名上传文件
        String imgName = file.getOriginalFilename();  //获取上传的图片名字

        String ext = "."+ FilenameUtils.getExtension(imgName);  //获取文件后缀名

        //通过该类生成一个唯一字符串,大概率不会重复但是为确保唯一性,最好在数据库编写一个表用来进行校验,这里本人没有使用
        String uuid= UUID.randomUUID().toString().replace("-",""); 

        String filName = uuid+ext; // 组合字符串得到文件名
        //阿里oss的地域节点,AccessKey的 ID和Secret
        String endpoint = "https://xxxxxxx";
        String accessKeyId = "xxxxxxxx";
        String accessKeySecret = "xxxxxxxx";
        //oss客户端对象
        //创建对象 三个参数 分别是 啊里云地域节点  以及AccessKey的 ID和Secret
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(
                "lyzhnb-blog",  // 阿里云oss的仓库名
                  filName,  // 文件名
                file.getInputStream()
        );
        ossClient.shutdown(); // 关闭OSS客户端对象
        return HTTP+filName;  //返回图片的地址  即图片的网上url
    }
    
}

3。编写测试接口

    @PostMapping("/list3")
               // MultipartFile file 是前端传来的文件
    public String get3(MultipartFile file) throws IOException {
                 return UpdateImg.uploadImage(file);
        }

 4.最后结果会得到一个存在阿里云的oss的图片URL

        本文到这里就结束了,最后还有就是发现,这里上传的文件大小有一定的限制,,如果超过文件大小可能会报错,希望大家们注意一下。

      如有不当之处请指出,勿喷

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值