vue3使用阿里oss上传资源(上传图片、视频、文件、pdf等等),删除oss资源。获取STS token的接口

发布于:2024-04-17 ⋅ 阅读:(19) ⋅ 点赞:(0)

vue3使用阿里oss上传资源

全部oss.ts代码如下:

import OSS from "ali-oss";

// 获取STS token
export const getSTSToken = async () => {
  const STS_TOKEN_URL = "....."; // 获取STS token的接口,后端提供
  // fetch方式可按需更换成axios
  const res = await fetch(STS_TOKEN_URL).then(res => res.json());
  const { stsToken, accessKeySecret, accessKeyId } = res.data || {};
  return {
    stsToken,
    accessKeySecret,
    accessKeyId
  };
};

// 初始化OSS client实例
export const initOSSClient = async () => {
  const token = await getSTSToken();
  // 可按需选择是挂载在window 还是其他变量上
  window.globalOSSClient = new OSS({
    region: "xxxxxxxx", //根据那你的Bucket地点来填写
    accessKeyId: token.accessKeyId, //自己账户的accessKeyId,这里getSTSToken通过后端获取
    accessKeySecret: token.accessKeySecret, //自己账户的accessKeySecret,这里getSTSToken通过后端获取
    stsToken: token.stsToken, // stsToken,这里getSTSToken通过后端获取
    refreshSTSToken: async () => {
      const tokenInfo = await getSTSToken();
      return tokenInfo;
    },
    // 刷新临时访问凭证的时间间隔,单位为毫秒。
    refreshSTSTokenInterval: 300000,
    bucket: "xxxxxxx" //bucket名字
    //secure: true, // 上传链接返回支持https
  });
};
// 删除oss的资源
export const delOSSUrl = url => {
  if (!url) return;
  const defaulUrl = new URL(url).origin + "/";
  const urlNew = url.replace(defaulUrl, "");
  window.globalOSSClient.delete(urlNew).then(res => {
    console.log("res", res);
  });
};
  1. 采用SDK的方法,先npm i ali-oss安装oss。

  2. 进入项目或者页面时,调用initOSSClient方法,初始化OSS client实例,从而获取STS token

  3. 当通过vantui或者elementui,或者其他方式拿到文件的file时,调用window.globalOSSClient.put(fileName, file)即可。

// 使用上传oss的页面
<script setup lang="ts" name="Tools">
import { onBeforeMount } from "vue";
import { initOSSClient, delOSSUrl } from "@/utils/oss.ts";
onBeforeMount(() => {
	//初始化OSS client实例
	initOSSClient();
});
// 需要上传的时候,调用
const putFileToOss= fileObj => {
  const { file } = fileObj;
  window.globalOSSClient
    .put(file.name, file)
    .then(res => {
      console.log("oss-res", res);
      const { url } = res;
      if (url) {
        userInfo.value.certificateImgs.push(url);
      }
    })
    .catch(() => {
      console.log("oss服务错误");
    });
};
// 在需要替换逻辑,或者删除逻辑的时候,记得调用delOSSUrl,删除oss上的资源
// delOSSUrl(url)
//
</script>