阿里云OSS对象存储的使用和实现万能文件上传和文件读取

 转载原文连接:http://t.csdnimg.cn/yNdDz 

阿里云OSS对象存储的使用和实现万能文件上传

==oss==是对象存储服务(Object Storage Service)的缩写,是一种分布式存储服务,用于存储和访问大规模数据。它提供了可靠、安全、低成本的数据存储解决方案,可以通过网络随时随地访问存储的数据。oss常用于存储图片、视频、文档等非结构化数据。

1、开通阿里云OSS对象存储服务(新用户可以免费试用三个月)

https://www.aliyun.com/product/oss?spm=5176.8465980.unusable.ddetail.7df51450v1aNb1 

1.1、点击免费试用并选择自己想要使用的服务

1.2、咱们这里选择使用第一个存储服务,然后点击立即试用

2、创建存储空间,获取bucketName和endpoint

存储空间(Bucket)是用于存储对象(Object)的容器。在上传任意类型的Object前,您需要先创建Bucket。

2.1、登录OSS管理控制台。

在左侧导航栏,单击Bucket列表,然后单击创建Bucket

创建Bucket面板,按如下说明配置必要参数。其他参数均可保持默认配置,也可以在Bucket创建完成后单独配置。然后单击确定

2.2、Bucket命名规则

同一阿里云账号在同一地域内创建的Bucket总数不能超过100个。Bucket创建后,其名称无法修改。==Bucket命名规则==如下:

命名示例

Bucket名称的==正确示例==如下:

> - examplebucket1

> - test-bucket-2021

>- aliyun-oss-bucket

Bucket名称的==错误示例==以及错误的原因如下:

- Examplebucket1(包含了大写字母)

>- test_bucket_2021(包含了下划线)

> - aliyun-oss-bucket-(结尾包含了短划线)

2.3、成功创建并进入Bucket

 

2.4、进入Bucket后查看概览,记录下图信息

 

 3、在阿里云网站上的个人中心配置Accesskey,查询accessKeyId和accessKeySecret。

 

3.1、进入AccssKey管理页面应该会出现下图提示,accessKeySecret为空,不用点击下载,直接确定即可

点击继续使用AccessKey

3.2、点击创建AccessKey

3.3、通过安全验证后可以看到生成的==accessKeyId和accessKeySecret==,大家下载csv文件或者复制下来,因为点击确定后==不再显示==accessKeySecret!!!

4、OSS的使用

4.1、导入依赖

<dependency>
       <groupId>com.aliyun.oss</groupId>
       <artifactId>aliyun-sdk-oss</artifactId>
       <version>3.10.2</version>
    </dependency>

 4.2、创建对应的工具类AliOssUtil类,此代码是固定代码,直接CV即可。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
//固定代码,CV直接使用
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes :传入的文件要转为byte[]
     * @param objectName :表示在oss中存储的文件名字。
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

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

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        return stringBuilder.toString();
    }
}

4.3、在该工具类中有四个属性,通过上面的步骤已经获得了我们上传图片到OSS所需要的四个参数:==bucketName、endpoint、accessKeyId、accessKeySecret==。这些属性需要我们手动在application.properties中配置。

# 配置阿里云OSS(application.properties)
aliyun.oss.bucketName = fpl1116-project
aliyun.oss.endpoint = oss-cn-zhangjiakou.aliyuncs.com
aliyun.oss.accessKeyId = 
aliyun.oss.accessKeySecret = 

# yml版(application.yml)
#aliyun:
#  oss:
#    bucketName: fpl1116-project
#    endpoint: oss-cn-zhangjiakou.aliyuncs.com
#    accessKeyId: 
#    accessKeySecret: 

 4.5、配置相应model类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * <p>Project: wms-project - OSSConfig</p>
 * <p>Powered by fpl1116 On 2024-02-28 23:26:54</p>
 * <p>描述:<p>
 *
 * @author penglei
 * @version 1.0
 * @since 1.8
 */

@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
public class AliOssProperties {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;


}

4.6、将工具类配置到ioc容器中,便于后续的使用

创建oss对应的配置类。

import com.fpl.model.AliOssProperties;
import com.fpl.utils.AliOssUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OssConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil getAliOssUtil(AliOssProperties aliOssProperties) {
//        log.info("创建OssUtil");
        AliOssUtil aliOssUtil = new AliOssUtil(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName()
        );
        return aliOssUtil;
    }
}

4.7、测试:创建控制层

@RestController
@RequestMapping("api/upload")
public class UploadController {

     @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/oss1")
    //万能上传
    public String upload1(@RequestBody UploadInfo uploadInfo){
        String name = uploadInfo.getName();
        String base64 = uploadInfo.getBase64();
        String[] base64Array = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(base64Array[1]);
        name = PinyinUtil.getPinyin(name, "");
        String newName = System.currentTimeMillis() +"_"+name;
        return aliOssUtil.upload1(bytes, newName);

    }
}

5、代码优化,将上面几个部分的代码融合到一个工具类中,application.properties配置文件中不变 

@Data
@Component
public class AliOssUtil {

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 文件上传
     *
     * @param bytes   :传入的文件要转为byte[]
     * @param newName :表示在oss中存储的文件名字。
     */
    public String upload1(byte[] bytes, String newName) {
        OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);
        try {
            // 创建PutObject请求。
            ossClient.putObject(this.bucketName, newName, new ByteArrayInputStream(bytes));
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(newName);

        return stringBuilder.toString();
    }
}

 6、实现阿里云OSS文件读取到咱们在咱们wms-project的图库中

6.1、在上面的工具类中添加下面代码

@Data

@Component


public class AliOssUtil {


    @Value("${aliyun.oss.bucketName}")

    private String bucketName;

    @Value("${aliyun.oss.endpoint}")

    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")

    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")

    private String accessKeySecret;

    @Value("${aliyun.oss.policy}")

    private String policy;



    /**

     * 文件上传

     *

     * @param bytes   :传入的文件要转为byte[]

     * @param newName :表示在oss中存储的文件名字。

     */

    public String upload1(byte[] bytes, String newName) {

        OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);

        try {

            // 创建PutObject请求。

            ossClient.putObject(this.bucketName, newName, new ByteArrayInputStream(bytes));

        } catch (Exception oe) {

            oe.printStackTrace();

        } finally {

            if (ossClient != null) {

                ossClient.shutdown();

            }

        }


        //文件访问路径规则 https://BucketName.Endpoint/ObjectName

        StringBuilder stringBuilder = new StringBuilder("https://");

        stringBuilder

                .append(bucketName)

                .append(".")

                .append(endpoint)

                .append("/")

                .append(newName);


        return stringBuilder.toString();

    }



    //查看oss
    public List<OSSObjectSummary> list() {

        OSS ossClient = new OSSClientBuilder().build(this.endpoint, this.accessKeyId, this.accessKeySecret);

//设置最大个数。

        final int maxKeys = 200;

// 列举文件。

        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));

        List<OSSObjectSummary> names = objectListing.getObjectSummaries();

        System.out.println(names);

        List<OSSObjectSummary> list = names.stream().map(name -> {

            OSSObjectSummary fileInfo = new OSSObjectSummary();

            fileInfo.setKey(name.getKey());

            System.out.println(name);

            if (name.getKey().contains(".xls")) {

                fileInfo.setKey(this.policy + "excel.jpg");

            } else {

                fileInfo.setKey(this.policy + name.getKey());

            }

            return fileInfo;

        }).collect(Collectors.toList());

        return list;

    }

}

6.2、在application.properties配置文件中添加aliyun.oss.policy(你创建bucket所给的域名) 

 

aliyun.oss.bucketName = fpl1116-project

aliyun.oss.endpoint = oss-cn-zhangjiakou.aliyuncs.com

aliyun.oss.accessKeyId = 

aliyun.oss.accessKeySecret = 

aliyun.oss.policy = https://fpl1116-project.oss-cn-zhangjiakou.aliyuncs.com/

6.3、在我们的前端TuKu.vue中修改数据源file.url---->file.key

<template #file="{ file }">
     <img class="el-upload-list__item-thumbnail img" 
		:src="file.key" 
		:title="file.name" 
		@click="pic(file)" />
</template>


const pic = (file: any) => {
    // imageUrl.value = file.url;
    imageUrl.value = file.key;
    drawer.value = false;
    // emit("update:modelValue", file.url);
    emit("update:modelValue", file.key);
};

实现上传图片时,图库中显示出我们在阿里云OSS中存储的资源

转载原文连接:http://t.csdnimg.cn/yNdDz

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值