• 阿里云OSS对象存储


    目录

     测试

    项目集成OSS

    准备工作 

    实现文件头像上传


    场景:利用阿里云OSS服务存储 

     

     测试

    依赖导入 

    1. <dependency>
    2. <groupId>com.aliyun.ossgroupId>
    3. <artifactId>aliyun-sdk-ossartifactId>
    4. <version>${aliyun.oss.version}version>
    5. dependency>
    6. <dependency>
    7. <groupId>junitgroupId>
    8. <artifactId>junitartifactId>
    9. <version>4.12version>
    10. dependency>

    测试

    利用密钥和地狱节点和key得到client

    1. package com.atguigu.oss;
    2. public class OSSTest {
    3. // Endpoint以杭州为例,其它Region请按实际情况填写。
    4. String endpoint = "your endpoint";
    5. // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
    6. String accessKeyId = "your accessKeyId";
    7. String accessKeySecret = "your accessKeySecret";
    8. String bucketName = "guli-file";
    9. @Test
    10. public void testCreateBucket() {
    11. // 创建OSSClient实例。
    12. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    13. // 创建存储空间。
    14. ossClient.createBucket(bucketName);
    15. // 关闭OSSClient。
    16. ossClient.shutdown();
    17. }
    18. }

    设置存储空间的访问权限

    1. @Test
    2. public void testAccessControl() {
    3. // 创建OSSClient实例。
    4. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    5. // 设置存储空间的访问权限为:公共读。
    6. ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    7. // 关闭OSSClient。
    8. ossClient.shutdown();
    9. }

    项目集成OSS

    准备工作 

     配置文件

    1. #服务端口
    2. server.port=8002
    3. #服务名
    4. spring.application.name=service-oss
    5. #环境设置:dev、test、prod
    6. spring.profiles.active=dev
    7. #阿里云 OSS
    8. #不同的服务器,地址不同
    9. aliyun.oss.file.endpoint=your endpoint
    10. aliyun.oss.file.keyid=your accessKeyId
    11. aliyun.oss.file.keysecret=your accessKeySecret
    12. #bucket可以在控制台创建,也可以使用java代码创建
    13. aliyun.oss.file.bucketname=guli-file

     OSS依赖导入

    1. <dependencies>
    2. <dependency>
    3. <groupId>com.aliyun.ossgroupId>
    4. <artifactId>aliyun-sdk-ossartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>joda-timegroupId>
    8. <artifactId>joda-timeartifactId>
    9. dependency>
    10. dependencies>

    启动项目

    这里需要注意我们没有配置数据源,所以需要@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)排除数据源配置

    1. package com.guli.oss;
    2. @SpringBootApplication
    3. @ComponentScan({"com.atguigu"})
    4. public class OssApplication {
    5. public static void main(String[] args) {
    6. SpringApplication.run(OssApplication.class, args);
    7. }
    8. }

    实现文件头像上传

    1.创建常量读取工具类:ConstantPropertiesUtil——>作用:读取application.properties里的配置内容,实现spring的 InitializingBean afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。

    1. /**
    2. * 常量类,读取配置文件application.properties中的配置
    3. */
    4. @Component
    5. //@PropertySource("classpath:application.properties")
    6. public class ConstantPropertiesUtil implements InitializingBean {
    7. @Value("${aliyun.oss.file.endpoint}")
    8. private String endpoint;
    9. @Value("${aliyun.oss.file.keyid}")
    10. private String keyId;
    11. @Value("${aliyun.oss.file.keysecret}")
    12. private String keySecret;
    13. @Value("${aliyun.oss.file.filehost}")
    14. private String fileHost;
    15. @Value("${aliyun.oss.file.bucketname}")
    16. private String bucketName;
    17. public static String END_POINT;
    18. public static String ACCESS_KEY_ID;
    19. public static String ACCESS_KEY_SECRET;
    20. public static String BUCKET_NAME;
    21. public static String FILE_HOST ;
    22. @Override
    23. public void afterPropertiesSet() throws Exception {
    24. END_POINT = endpoint;
    25. ACCESS_KEY_ID = keyId;
    26. ACCESS_KEY_SECRET = keySecret;
    27. BUCKET_NAME = bucketName;
    28. FILE_HOST = fileHost;
    29. }
    30. }

    2.文件上传接口

    1. public interface FileService {
    2. /**
    3. * 文件上传至阿里云
    4. * @param file
    5. * @return
    6. */
    7. String upload(MultipartFile file);
    8. }

    3.文件上传业务实现

    思路:初始化OssClient,然后实现权限设置——>文件流+文件名称设置(组成uuid保证唯一性+时间进行分类)——>然后调用ossClient的api进行存储,返回我们的结合了oss的文件url

    1. package com.atguigu.oss.service.impl;
    2. import com.aliyun.oss.OSS;
    3. import com.aliyun.oss.OSSClientBuilder;
    4. import com.atguigu.oss.service.OssService;
    5. import com.atguigu.oss.utils.ConstantPropertiesUtils;
    6. import org.joda.time.DateTime;
    7. import org.springframework.stereotype.Service;
    8. import org.springframework.web.multipart.MultipartFile;
    9. import java.io.IOException;
    10. import java.io.InputStream;
    11. import java.util.UUID;
    12. @Service
    13. public class OssServiceImpl implements OssService {
    14. /**
    15. * 1.上传头像到Oss
    16. * @param file
    17. * @return
    18. */
    19. @Override
    20. public String uploadFileAvatar(MultipartFile file) {
    21. //1.获取阿里云存储相关常量
    22. String endPoint = ConstantPropertiesUtils.END_POINT;
    23. String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
    24. String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
    25. String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
    26. //2.创建Oss实例
    27. OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
    28. try {
    29. //3.获取上传文件流
    30. InputStream inputStream = file.getInputStream();
    31. //4.获取文件名称
    32. String fileName = file.getOriginalFilename();
    33. /**
    34. * 4.1对文件名称进行操作,利用uuid生成唯一值,目的防止图片覆盖
    35. * 00820asjoa01.jpg
    36. */
    37. String uuid= UUID.randomUUID().toString().replace("-","");
    38. fileName=uuid+fileName;
    39. /**
    40. * 5.2把文件按照日期进行分类
    41. * 1.获取当前路径
    42. * 2.然后进行拼接
    43. * https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
    44. */
    45. String datePath = new DateTime().toString("yyyy/MM/dd");
    46. fileName=datePath+"/"+fileName;
    47. /**
    48. * 5.调用oss方法实现上传
    49. * 第一个参数为bucket名称,第二个是上传到oss文件路径和文件名称,第三个是输入流
    50. */
    51. ossClient.putObject(bucketName,fileName,inputStream);
    52. //6.关闭OssClient
    53. ossClient.shutdown();
    54. /**
    55. * 7.通过oss规则拼接url
    56. * https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
    57. * https://edu-wyh.oss-cn-beijing.aliyuncs.com/01.png
    58. */
    59. String url="https://"+bucketName+"."+endPoint+"/"+fileName;
    60. return url;
    61. } catch (Exception e) {
    62. e.printStackTrace();
    63. return null;
    64. }
    65. }
    66. }

    3.文件上传控制层

    1. package com.atguigu.oss.controller;
    2. import com.atguigu.eduservice.R;
    3. import com.atguigu.oss.service.OssService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.CrossOrigin;
    6. import org.springframework.web.bind.annotation.PostMapping;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import org.springframework.web.multipart.MultipartFile;
    10. @RestController
    11. @RequestMapping("/eduoss/fileoss")
    12. @CrossOrigin
    13. public class OssController {
    14. @Autowired
    15. private OssService ossService;
    16. /**
    17. * 1.上传头像
    18. */
    19. @PostMapping
    20. public R uploadOssFile(MultipartFile file){
    21. //获取上传文件
    22. //返回url头像路径
    23. String url=ossService.uploadFileAvatar(file);
    24. return R.ok().data("url",url);
    25. }
    26. }

     访问我们的路径可以得到图片

     

  • 相关阅读:
    230. 二叉搜索树中第K小的元素 Python
    jira+confluence安装
    Go分布式缓存 使用 Protobuf 通信(day7)
    2024黑马AI+若依框架项目开发 个人心得、踩坑和bug记录 全网最快最全 基础功能认识篇
    Flutter循序渐进==>数据结构(列表、映射和集合)和错误处理
    Packet Tracer - 使用 Traceroute 发现网络
    wireshark 流量抓包例题重现
    [JavaWeb] web的基本概念
    关于C2447 “{”: 缺少函数标题(是否是老式的形式表?)
    【Java毕设项目合集】26款Java毕设项目合集
  • 原文地址:https://blog.csdn.net/weixin_57128596/article/details/126066408