使用阿里云对象存储OSS收藏老婆新垣结衣日常照

阿里云OSS官方文档

官方文档

开通阿里云OSS服务

先进入控制台,点击菜单栏的对象存储 OSS,根据提示开通服务。

在这里插入图片描述

阿里云OSS 学习路径

入门使用

使用步骤

  1. 首先创建一个Bucket在这里插入图片描述
    在这里插入图片描述

  2. 使用OOS

在这里插入图片描述
3. 上传文件

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

java代码上传文件至OSS

API文档

1、准备工作:创建阿里云OSS许可证(获取对Api的访问权限)

在这里插入图片描述

选择继续使用 AccessKey

在这里插入图片描述

创建AccessKey

在这里插入图片描述

创建成功

在这里插入图片描述

springBoot整合OSS

依赖

<dependencies>
        <!-- 阿里云oss依赖 -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>${aliyun.oss.version}</version>
        </dependency>

        <!-- 日期工具栏依赖 -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
    </dependencies>

配置文件 application.yaml

server:
  port: 8002
spring:
  application:
    name: service-oss
  profiles:
    active: dev

## 阿里云 OSS
aliyun:
  oss:
    file:
      endpoint: oss-cn-beijing.aliyuncs.com # 地域节点
      keyid: LTAI5tFNjjg1s5mxxDC6Rxc4 # AccessKeyId
      keysecret: fZvVNtbU8pNfmAxxx53jYXhMUVHOo8 # 密钥
      bucketname: edu-xiuyuan # bucket名字

常量工具类

package com.zlf.oss.utils;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: zlf
 * @Date: 2021/03/22/20:01
 * @Description: 读取常量的工具类
 */

/**
 * InitializingBean 实现该接口 在SpringBoot项目初始化时会初始化将配置文件中的值赋给对应属性
 */
@Component
public class ConstantPropertiesUtils 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;

    public static String END_POINT;

    public static String KEY_ID;

    public static String KEY_SECRET;

    public static String BUCKET_NAME;

    /**
    * @Description: 属性赋值后,会执行该方法初始化静态成员
    * @Param: []
    * @return: void
    * @Author: zlf
    * @Date: 2021/3/22
    */
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endPoint;
        KEY_ID = keyId;
        KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

OssController

package com.zlf.oss.Controller;

import com.zlf.commonutils.Response.R;
import com.zlf.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: zlf
 * @Date: 2021/03/22/20:16
 * @Description: 阿里云oss  上传文件
 */
@RestController
@RequestMapping("/eduOss/fileOss")
@CrossOrigin
@Api(description = "oss上传接口")
public class OssController {


    @Autowired
    private OssService ossService;

    /**
    * @Description: 上传头像
    * @Param: [file]
    * @return: com.zlf.commonutils.Response.R
    * @Author: zlf
    * @Date: 2021/3/22
    */
    @PostMapping("uploadFile")
    @ApiOperation("上传文件")
    public R uploadOssFile(@ApiParam(name = "file",value = "文件") MultipartFile file)  {
        //获取上传对象
        String url = null;
        try {
            url = ossService.uploadFileAvatar(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().data("url",url);
    }
}

OssService

package com.zlf.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.zlf.oss.service.OssService;
import com.zlf.oss.utils.ConstantPropertiesUtils;
import com.zlf.servicebase.exceptionHandler.GlobalException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: zlf
 * @Date: 2021/03/22/20:15
 * @Description:
 */
@Service
public class OssServiceImpl implements OssService {
    
    /**
    * @Description: 上传文件到阿里云oss
    * @Param: [file]
    * @return: 文件 url
    * @Author: zlf
    * @Date: 2021/3/22
    */
    @Override
    public String uploadFileAvatar(MultipartFile file)  {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

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

            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();

            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 在文件名称中添加一个唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            // 按照时间日期进行分类 如 / 2021/03/22/xxx.jpg
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath  +"/"+  fileName;
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。以及上传文件的文件流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传路径返回 (手动拼接返回)

            //模板 https://edu-xiuyuan.oss-cn-beijing.aliyuncs.com/2021/03/20/%E6%96%B0%E6%A1%93%E7%BB%93%E8%A1%A3.png
            String url = "https://"+ bucketName +"."+ endpoint + "/" +fileName;
            return url;

        }catch (Exception e){
            e.printStackTrace();
           return null;
        }

    }
}


详细的Api接口参考官方文档

效果

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

结尾

其他功能的实现请参考官方文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值