阿里云OSS的使用(全程请登陆)


个人博客网站: https://xingkongdiyiren.github.io/myblog/,完整的Java知识体系,包括408,架构,业务,产品,软技能等

1、阿里云oss服务开通

点击开通:https://www.aliyun.com/ss/?spm=5176.22772544.J_8058803260.37.4aa92ea9DAomsC&k=OSS

2、进入控制台

点击进入:https://oss.console.aliyun.com/overview?spm=5176.10695662.5694434980.5.735b30bePm5pgo

3、创建Bucket

点击进入bucket:https://oss.console.aliyun.com/bucket
按照下面选择就行,主要是红框里面的要选,其他默认就行,都是不开通或者关闭,其中名称自己命名,地址选自己所在区域(这会快很多)。
在这里插入图片描述

4、上传一张图片,测试是否成功

在这里插入图片描述
文件管理-》点击图片详情,然后用url去访问:
在这里插入图片描述
就可以下载成功!!!说明可以访问!!!!

5、创建AccessKey

1、点击头像:url直达->https://ram.console.aliyun.com/manage/ak
在这里插入图片描述
在这里插入图片描述
上面这个access key是下面操作的关键
温馨提示:不要用我的,我写完博客就删,换个新的!!!!

AccessKey IDLTAI5t6pkvY99BLYA5MSXWzA
AccessKey Secret5SSwHf8GWg6siJHFH3ylcpJd7eEy9q

上代码!!!!!

6、Java集成OSS

官网参考链接:https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.918.76fe46a1upTv30

6.1、依赖POM

			<!--aliyunOSS-->
            <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>
                <version>2.10.1</version>
            </dependency>

6.2、配置类application.yml

# 服务端口
server:
  port: 8002
spring:
  application:
    name: service-oss # 服务名
  profiles:
    active: dev # 环境配置:dev,test,prod
# 集成阿里云OSS=>不同的服务器,地址不同
aliyun:
  oss:
    file:
      endpoint: oss-cn-beijing.aliyuncs.com # 对应公网endpoint地址
      keyid: LTAI5t6pkvY99BLYA5MSXWzA
      keysecret: 5SSwHf8GWg6siJHFH3ylcpJd7eEy9q
      bucketname: zhz-mail  #可以代码层面实现

6.3、创建启动类

package com.zhz.oss;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author zhouhengzhe
 * @Description: 启动类
 * @date 2021/6/29上午1:42
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//加这个是为了排除数据库
@ComponentScan(basePackages = {"com.zhz"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class,args);
    }
}

6.4、创建一个读取配置的类

package com.zhz.oss.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author zhouhengzhe
 * @Description: 读取oss配置信息,当项目已启动,Spring接口,Spring加载之后,执行接口的一个方法
 * @date 2021/6/29上午1:47
 */
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantPropertiesUtils implements InitializingBean {

    /**
     * 对应公网endpoint地址
     */
    @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 ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

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


6.5、controller

package com.zhz.oss.controller;

import com.zhz.common.utils.R;
import com.zhz.oss.service.OssService;
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;

/**
 * @author zhouhengzhe
 * @Description: Oss控制器类
 * @date 2021/6/29上午1:56
 */
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {

    @Autowired
    private OssService ossService;
    /**
     * 上传头像
     */
    @PostMapping("")
    public R uploadOSSFile(MultipartFile file){
        //获取上传文件 MultipartFile
        //返回上传到oss的路径
        String url=ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}

6.6、service

package com.zhz.oss.service;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author zhouhengzhe
 * @Description: 文件上传oss处理类接口
 * @date 2021/6/29上午1:58
 */
public interface OssService {

    /**
     * 上传头像到oss
     * @param file 文件对象
     * @return
     */
    String uploadFileAvatar(MultipartFile file);
}

6.7、service.impl

package com.zhz.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zhz.oss.service.OssService;
import com.zhz.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author zhouhengzhe
 * @Description: 上传文件到oss的处理类
 * @date 2021/6/29上午2:01
 */
@Service
public class OssServiceImpl implements OssService {
    /**
     * 上传头像到oss
     *
     * @param file 文件对象
     * @return
     */
    @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.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        //块名
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            //获取文件真实名称
            String originalFilename = file.getOriginalFilename();
            //重命名,防止相同文件出现覆盖 生成的f4f2e1a3-391a-4d5a-9438-0c9f5d27708=》需要替换成f4f2e1a3391a4d5a94380c9f5d27708c
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //新的文件名
            originalFilename=uuid+originalFilename;
            //2、把文件按照日期进行分类
            // 2021/6/30
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接 021/6/30/1.jpg
            originalFilename=datePath+"/"+originalFilename;
            // oss实现上传文件
            //第一个参数:Bucket名称
            //第二个参数:上传到oss文件路径和文件名称 /zhz/avatar.txt
            ossClient.putObject(bucketName, originalFilename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来->https://zhz-mail.oss-cn-beijing.aliyuncs.com/WechatIMG19.jpeg
            String url="https://"+bucketName+"."+endpoint+"/"+originalFilename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

6.8、测试

因为我是集成了swagger的,所以我可以通过swagger测试

在这里插入图片描述

6.9、Nginx反向代理

第一步,修改默认端口:
为什么要改成81呢,是因为后面如果要用网关,网关一般都是80,所以就改了

http {
    server {
listen 81;
......
},
...
server {
    listen 8201;
    server_name www.zhzmail.com;
    location ~ /eduoss/ {
         proxy_pass http://localhost:8002;
    }
} }

然后我就可以简写成www.zhzmail.com去不写我的ip+端口了

7、其余,swagger集成,R类统一返回,统一日志等,请看我其他博客

统一日志:https://blog.youkuaiyun.com/zhouhengzhe/article/details/118078080
统一返回值:https://blog.youkuaiyun.com/zhouhengzhe/article/details/118065066
统一异常:https://blog.youkuaiyun.com/zhouhengzhe/article/details/118064739
swagger集成:https://blog.youkuaiyun.com/zhouhengzhe/article/details/118063779

下面是本人的公众号:(有兴趣可以扫一下,文章会同步过去)
在这里插入图片描述

我是小白弟弟,一个在互联网行业的小白,立志成为一名架构师
https://blog.youkuaiyun.com/zhouhengzhe?t=1

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zhz小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值