springboot中上传图片到阿里云的oss云存储

上篇演示了如何将图片上传到本地,但是在实际项目中,这样是很占服务器存储空间的。所以,我们一般的解决方案是使用oss云存储。这里就结合阿里云的oss来实现下这个业务功能。

在这里插入图片描述

安装依赖

参考官网即可,https://help.aliyun.com/zh/oss/developer-reference/java-installation?spm=a2c4g.11186623.0.0.5e2f480coYc6ZA
在这里插入图片描述

 <dependency>
     <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.17.4</version>
  </dependency>

代码实现

/**
     * 上传到阿里云oss
     * @param image
     * @return
     * @throws Exception
     */

    @PostMapping
    public Result upload(MultipartFile image) throws Exception {
        log.info("文件上传成功 {}",image.getOriginalFilename());
        String originalFilename = image.getOriginalFilename();
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
  • 封装阿里云的oss上传方法
    bucketName ,accessKeyId,accessKeySecret一定要用自己申请到的
package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
    private String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
    // 填写Bucket名称,例如examplebucket。
    private String bucketName = ";
    private String accessKeyId = "";
    private String accessKeySecret = "";

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName, filename, inputStream);
        String url = endpoint.split("//")[0] + "//"  + bucketName + "." + endpoint.split("//")[1] +"/" + filename;
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}

根据不同的上传需求,选择官网写好的demo代码,demo链接
https://help.aliyun.com/zh/oss/developer-reference/simple-upload-11?spm=a2c4g.11186623.0.0.610d23bfPTrcOO#section-nwx-2uy-oqp
在这里插入图片描述

  • 上传成功后,在bucket列表里面查看上传的文件列表
    在这里插入图片描述
    点击文件右边的详情,就能看到具体信息
    在这里插入图片描述
    这样,我们在新增/编辑员工信息的时候,就可以增加员工的头像图片了

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
正常情况下,我们在列表中就能看到新增的这条数据了。

在这里插入图片描述
数据库中的信息,这样也就完成了文件上传的基础功能
在这里插入图片描述


代码优化

配置信息,现在我们还写在工具类里面,硬编码了,这样不利于维护,于是我们改造代码,使用springboot的注解来解耦
在这里插入图片描述
用自己申请大账号,注意不要引号和分号,否则会报错

# 阿里云oss的配置
aliyun.oss.bucketName = 
aliyun.oss.accessKeyId = 
aliyun.oss.accessKeySecret = 
aliyun.oss.endpoint = 

工具类方法
@Value是引用的import org.springframework.beans.factory.annotation.Value;,不是lombok里面的

package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName, filename, inputStream);
        String url = endpoint.split("//")[0] + "//"  + bucketName + "." + endpoint.split("//")[1] +"/" + filename;
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}

在这里插入图片描述

重启服务,测试后一切正常。
在这里插入图片描述

  • 自定义的阿里云配置信息爆红的解决方法
 <dependency>
    <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
 </dependency>

重新启动,在重新输入即可
在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值