springboot整合阿里云OSS存储

开通阿里云OSS对象存储

1、进入管理控制台

在这里插入图片描述

2、 创建Bucket

在这里插入图片描述

3、配置属性(根据个人需求设置)

在这里插入图片描述

4、查看个人bucket

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

5、springboot配置

(1)引入依赖

		<!--aliyun oss存储-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--日期工具类-->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

(2)配置yml文件

#阿里云OSS存储配置
aliyun:
  oss:
    file:
      endpoint: oss-cn-shenzhen.aliyuncs.com
      keyid: your AccessKeyID
      keysecret: your keySecret
      bucketname: your bucketname
      url: https://bucketName.endpoint/

(3)编写配置类

package com.siko.education.config;

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author barry
 * @create 2022-04-27 22:19
 */
//当项目已启动,spring接口,spring加载之后,执行接口一个方法

@Configuration
public class OSSConfig implements InitializingBean {
    //读取配置文件内容
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Value("${aliyun.oss.file.url}")
    private String url;

    //定义公开静态常量
    public static String END_POIND;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;
    public static String URL;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POIND = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
        URL=url;
    }
}

(4)编写controller层

package com.siko.education.controller;

import com.siko.education.service.OSSService;
import com.siko.education.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author barry
 * @create 2022-04-27 22:44
 */
@RestController
@RequestMapping("/edu/oss")
public class OSSController {
    @Autowired
    private OSSService ossService;
    /**
     * 上传文件至阿里云 oss
     *
     * @param file
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/upload", produces = {MediaType.APPLICATION_JSON_VALUE})
    public R uploadOssFile(MultipartFile file){
        if(file == null){
            return R.error();
        }
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}

(5)service层

package com.siko.education.service;

import com.siko.education.util.R;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author barry
 * @create 2022-04-27 22:32
 */
public interface OSSService {

    /**
     * 上传文件至阿里云 oss
     */
    String uploadFileAvatar(MultipartFile file);
}

(6)serviceImpl

package com.siko.education.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.siko.education.config.OSSConfig;
import com.siko.education.service.OSSService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author barry
 * @create 2022-04-27 22:33
 */
@Service("ossService")
public class OSSServiceImpl implements OSSService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = OSSConfig.END_POIND;
        String accessKeyId = OSSConfig.ACCESS_KEY_ID;
        String accessKeySecret = OSSConfig.ACCESS_KEY_SECRET;
        String bucketName = OSSConfig.BUCKET_NAME;
        String baseUrl = OSSConfig.URL;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            //避免文件上重复名称 增加uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid + fileName;

            //对上传的文件加上日期分类
            String datePath = new DateTime().toString("yyyy-MM-dd");
            fileName = datePath +"/"+ fileName;

            /**
             * 第一个参数 BucketName名称
             * 第二个参数 上传到oss文件的文件名称
             * 第三个参数 上传文件输入流
             */
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
            return baseUrl+ fileName;
        } catch (Exception ce) {
            ce.printStackTrace();
            System.out.println("Error Message:" + ce.getMessage());
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

(7)测试
在这里插入图片描述

上传成功!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
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* [全网最详细SpringBoot、SpringCloud整合阿里云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 ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值