阿里云OSS对象存储

目录

 测试

项目集成OSS

准备工作 

实现文件头像上传


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

 

 测试

依赖导入 

  <!--aliyunOSS-->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>${aliyun.oss.version}</version>
            </dependency>
          <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>4.12</version>
          </dependency>

测试

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

package com.atguigu.oss;

public class OSSTest {

    // Endpoint以杭州为例,其它Region请按实际情况填写。
    String endpoint = "your endpoint";
    // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
    String accessKeyId = "your accessKeyId";
    String accessKeySecret = "your accessKeySecret";
    String bucketName = "guli-file";

    @Test
    public void testCreateBucket() {

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

        // 创建存储空间。
        ossClient.createBucket(bucketName);

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

设置存储空间的访问权限

@Test
public void testAccessControl() {

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

    // 设置存储空间的访问权限为:公共读。
    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

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

项目集成OSS

准备工作 

 配置文件

#服务端口
server.port=8002
#服务名
spring.application.name=service-oss

#环境设置:dev、test、prod
spring.profiles.active=dev
        
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file

 OSS依赖导入

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

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

启动项目

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

package com.guli.oss;
@SpringBootApplication
@ComponentScan({"com.atguigu"})
public class OssApplication {

    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

实现文件头像上传

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

/**
 * 常量类,读取配置文件application.properties中的配置
 */
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil 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.filehost}")
	private String fileHost;

	@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;
	public static String FILE_HOST ;

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

2.文件上传接口

public interface FileService {

	/**
	 * 文件上传至阿里云
	 * @param file
	 * @return
	 */
	String upload(MultipartFile file);
}

3.文件上传业务实现

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

package com.atguigu.oss.service.impl;

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

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

@Service
public class OssServiceImpl implements OssService {

    /**
     * 1.上传头像到Oss
     * @param file
     * @return
     */
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //1.获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        //2.创建Oss实例
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        try {
            //3.获取上传文件流
            InputStream inputStream = file.getInputStream();

            //4.获取文件名称
            String fileName = file.getOriginalFilename();

            /**
             * 4.1对文件名称进行操作,利用uuid生成唯一值,目的防止图片覆盖
             * 00820asjoa01.jpg
             */
            String uuid= UUID.randomUUID().toString().replace("-","");
            fileName=uuid+fileName;

            /**
             * 5.2把文件按照日期进行分类
             * 1.获取当前路径
             * 2.然后进行拼接
             * https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
             */
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+"/"+fileName;


            /**
             * 5.调用oss方法实现上传
             * 第一个参数为bucket名称,第二个是上传到oss文件路径和文件名称,第三个是输入流
             */
            ossClient.putObject(bucketName,fileName,inputStream);

            //6.关闭OssClient
            ossClient.shutdown();

            /**
             * 7.通过oss规则拼接url
             * https://edu-wyh.oss-cn-beijing.aliyuncs.com/2022/07/10/743b170599cb434ba97fb90c335a9e4902.png
             * https://edu-wyh.oss-cn-beijing.aliyuncs.com/01.png
             */
            String url="https://"+bucketName+"."+endPoint+"/"+fileName;

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

    }
}

3.文件上传控制层

package com.atguigu.oss.controller;

import com.atguigu.eduservice.R;
import com.atguigu.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;

@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {

    @Autowired
    private OssService ossService;

    /**
     * 1.上传头像
     */
    @PostMapping
    public R uploadOssFile(MultipartFile file){
        //获取上传文件
        //返回url头像路径
        String url=ossService.uploadFileAvatar(file);

        return R.ok().data("url",url);
    }

}

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

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>