OSS对象存储的简单实现

这篇具有很好参考价值的文章主要介绍了OSS对象存储的简单实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前提准备好阿里云对象存储的账号->创建一个bucket(设置好访问权限)->创建用于上传文件的子账号得到accessKey和secretKey以及endpoint->sdk例子java简单上传的例子测试

  1. 引入alicloud-oss对象纯存储相关的依赖

  1. 在application.yml中配置accessKey和secretKey即可

  1. 使用OssClient对象调用方法上传即可

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        //accessKey和secretKey以及endpoint在配置文件中指定的话这里就不用重复指定
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "D:\\localpath\\examplefile.txt";

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

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置,则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功,则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } 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();
            }
        }
    }
} 

一,项目结合实例

先发送请求获得policy 在将对象发送阿里云对象存储服务器 减轻后端压力

建立一个oss服务器

将oss相关配置写在配置文件中

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    application:
      name: gulimall-third-party
    alicloud:
      access-key: LTAI5t6G5JAZ9RB*********** # 修改为自己的
      secret-key: QhhibxJFoXR9qUs*********** # 修改为自己的
      oss:
        endpoint: oss-cn-************* # 修改为自己的
        bucket: test # 修改为自己的
server:
  port: 30000

编写controller前端请求这个controller获得policy

package com.wcw.gulimall.third.party.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

import com.wcw.gulimall.third.party.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName com.wcw.gulimall.third.party.controller.OssController
 * @Description:
 * @Author wcw
 * @Version V1.0 Created on :2023/3/2 17:25
 */
@RestController
public class OssController {
    @Autowired
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endPoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/oss/policy")
    public R policy() {
        // 填写Host地址,格式为https://bucketname.endpoint。
        String host = "https://" + bucket + "." + endPoint;
        // 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
//        String callbackUrl = "https://192.168.0.0:8888";
        // 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format+"/";
        Map<String, String> respMap = new LinkedHashMap<String, String>();

        // 创建ossClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap.put("accessId", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
        return R.ok().put("data",respMap);
    }
}

返回下面的对象

{ policy: '',
 signature: '',
key: '',
ossaccessKeyId: '',
 dir: '',
 host: '',}

携带policy按照aliyun oss官方文档发送即可文章来源地址https://www.toymoban.com/news/detail-755725.html

<template> 
  <div>
    <el-upload
      action="http://gulimall-wcw.oss-cn-chengdu.aliyuncs.com"
      :data="dataObj"
      list-type="picture"
      :multiple="false" :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
   import {policy} from './policy'
   import { getUUID } from '@/utils'

  export default {
    name: 'singleUpload',
    props: {
      value: String
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value !== null && this.value !== ''&& this.value!==undefined;
        },
        set: function (newValue) {
        }
      }
    },
    data() {
      return {
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: '',
          // callback:'',
        },
        dialogVisible: false
      };
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        
        let _self = this;
        return new Promise((resolve, reject) => {
          policy().then(response => {
            console.log("response:",response);
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessId;
            _self.dataObj.key = response.data.dir +getUUID()+'_${filename}';
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            console.log("_self.dataObj:",_self.dataObj);
            resolve(true)
          }).catch(err => {
            reject(false)
          })
        })
      },
      handleUploadSuccess(res, file) {
        console.log("上传成功...")
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) });
        this.emitInput(this.fileList[0].url);
      }
    }
  }
</script>
<style>

</style>


到了这里,关于OSS对象存储的简单实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 阿里云对象存储OSS使用

    对象存储服务(Object Storage Service,简称 OSS)为您提供基于网络的数据存取服务。使用 OSS,您可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种非结构化数据文件。 对象存储可以简单理解为用来存储图片、音频、视频等非结构化数据的数据池。相对于主

    2024年02月11日
    浏览(40)
  • 阿里云对象存储(OSS)服务

    阿里云对象存储(OSS)服务 引入依赖 这里 aliyun-oss-spring-boot-starter 中默认引入的 aliyun-java-sdk-core 是 3.4.0 版本,但是 aliyun-spring-boot-dependencies 中对 aliyun-java-sdk-core 版本管理为:4.5.0,会导致版本冲突 所以排除 aliyun-oss-spring-boot-starter 默认的 aliyun-java-sdk-core ,单独引入 4.5.0 版

    2024年01月25日
    浏览(34)
  • 2.阿里云对象存储OSS

            文件上传,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发抖音、发朋友圈都用到了文件上传功能。 实现文件上传服务,需要有存储的支持,解决方案有以下几种: 存储方式

    2024年02月12日
    浏览(39)
  • 阿里云对象存储OSS怎么收费?

    阿里云对象存储OSS收费有两种计费模式,即包年包月和按量付费,包年包月是指购买存储包、流量包来抵扣OSS产生的存储费核流量费,OSS标准(LRS)存储包100GB优惠价33元、500GB存储包半年162元、OSS存储包40GB一年9元,OSS流量包100G 49元/月,阿里云百科来详细说下阿里云对象存储

    2024年01月19日
    浏览(40)
  • 浅谈阿里云对象存储OSS

    OSS(即Object Storage Service)是一种提供海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本,官方一点解释就是对象存储是一种使用HTTP API存储和检索非结构化数据和元数据对象的工具。白

    2024年02月12日
    浏览(45)
  • 阿里云对象存储OSS文件上传

    阿里云oss地址: 对象存储OSS_云存储服务_企业数据管理_存储-阿里云 阿里云对象存储OSS是一款海量、安全、低成本、高可靠的云存储服务,提供12个9的数据持久性,99.995%的数据可用性和多种存储类型,适用于数据湖存储,数据迁移,企业数据管理,数据处理等多种场景,可对

    2024年02月12日
    浏览(32)
  • 阿里云oss对象存储的使用

    1.介绍 对象存储服务(Object Storage Service,OSS)是一种海量、安全、低成本、高可靠的云存储 服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优 化存储成本。 2.使用步骤   1)登录阿里云:https://www.aliyun.com   2)开通阿里云对象存储服

    2024年01月17日
    浏览(36)
  • 阿里云对象存储OSS学习笔记4

    存储类型介绍: 文件存储:NAS 文件存储、NFS。 块存储:SAN iSCSI: 硬盘通过IP的方式提供给其他设备使用。 对象存储:OSS、CUS:我们创建了一个存储池,我们的文件有文件本身、给文件生成元数据、文件唯一的ID。我们可以通过http和https来阅读。存储内容:内容不会变化的,例

    2024年02月06日
    浏览(36)
  • SpringBoot集成-阿里云对象存储OSS

    阿里云对象存储 OSS (Object Storage Service),是一款海量、安全、低成本、高可靠的云存储服务。使用 OSS,你可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种文件。 登录阿里云后进入阿里云控制台首页选择 对象存储 OSS 服务 开通服务 创建Bucket 填写

    2024年02月06日
    浏览(36)
  • SpringBoot整合阿里云OSS对象存储

    阿里云对象存储服务(Object Storage Service,简称OSS)为您提供基于网络的数据存取服务。使用OSS,您可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种非结构化数据文件。 阿里云OSS将数据文件以对象(object)的形式上传到存储空间(bucket)中。 可以进行

    2024年02月06日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包