npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@be-link/cos

v1.12.12

Published

前端项目产物上传cos

Readme

@be-link/cos

腾讯云 COS 浏览器端文件上传工具。

功能特性

  • 🌐 浏览器端上传 - 单文件上传,支持进度回调
  • 🔐 安全可靠 - 自动获取临时密钥,无需暴露永久密钥
  • 性能优化 - 大文件 MD5 分片计算,避免内存溢出
  • 📝 TypeScript - 完整的类型定义支持
  • 🎯 多环境 - 支持开发、测试、生产环境配置
  • 🔧 安全设计 - mode 必填无默认值,强制显式配置,避免环境配置错误

安装

npm install @be-link/cos cos-js-sdk-v5 crypto-js

快速开始

💡 提示:本包提供两种使用方式

  1. 全局单例模式beLinkCOS):向后兼容,适合全局统一配置
  2. 类实例模式BeLinkCOS):推荐方式,支持多实例

方式一:全局单例模式(向后兼容)

适合全局统一配置的场景,在 main.ts/main.tsx 中初始化:

// main.ts
import { beLinkCOS } from '@be-link/cos';

// 初始化全局单例
beLinkCOS.init({
  mode: 'production',
  projectName: 'be-link-live-h5', // 可选,特定项目使用专用桶
});

// 之后在任何地方都可以直接使用
// 组件中:
const result = await beLinkCOS.uploadFile(file);

方式二:类实例模式(推荐)

支持创建多个实例,适合需要不同配置的场景:

Vue 项目

立即初始化

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="handleUpload" :disabled="uploading">
      {{ uploading ? `上传中 ${progress}%` : '上传文件' }}
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { BeLinkCOS } from '@be-link/cos';

const file = ref(null);
const uploading = ref(false);
const progress = ref(0);

// 创建上传器实例(mode 必填)
const uploader = new BeLinkCOS({ mode: 'production' });

const handleFileChange = (e) => {
  file.value = e.target.files[0];
};

const handleUpload = async () => {
  if (!file.value) return;

  uploading.value = true;
  try {
    const result = await uploader.uploadFile(file.value, {
      onProgressCallback: (data) => {
        progress.value = Math.round(data.percent * 100);
      },
    });
    console.log('上传成功:', result.url);
  } catch (error) {
    console.error('上传失败:', error);
  } finally {
    uploading.value = false;
  }
};
</script>

延迟初始化(支持异步配置)

<script setup>
import { ref, onMounted } from 'vue';
import { BeLinkCOS } from '@be-link/cos';

const uploader = new BeLinkCOS(); // 先创建实例

onMounted(async () => {
  // 从服务器获取配置
  const config = await fetchConfigFromServer();
  uploader.init({ mode: config.mode }); // 稍后初始化
});

const handleUpload = async () => {
  const result = await uploader.uploadFile(file.value);
  console.log('上传成功:', result.url);
};
</script>

React 项目

import { useState } from 'react';
import { BeLinkCOS } from '@be-link/cos';

// 创建上传器实例(mode 必填)
const uploader = new BeLinkCOS({ mode: 'production' });

function FileUploader() {
  const [file, setFile] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);

  const handleUpload = async () => {
    if (!file) return;

    setUploading(true);
    try {
      const result = await uploader.uploadFile(file, {
        onProgressCallback: (data) => setProgress(Math.round(data.percent * 100)),
      });
      console.log('上传成功:', result.url);
    } catch (error) {
      console.error('上传失败:', error);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div>
      <input type='file' onChange={(e) => setFile(e.target.files[0])} />
      <button onClick={handleUpload} disabled={uploading}>
        {uploading ? `上传中 ${progress}%` : '上传文件'}
      </button>
    </div>
  );
}

原生 JS

<!DOCTYPE html>
<html>
  <head>
    <script type="module">
      import { BeLinkCOS } from '@be-link/cos';

      // 创建上传器实例(mode 必填)
      const uploader = new BeLinkCOS({ mode: 'production' });

      // 上传
      document.getElementById('upload').onclick = async () => {
        const file = document.getElementById('file').files[0];
        const result = await uploader.uploadFile(file, {
          onProgressCallback: (data) => {
            console.log('进度:', data.percent * 100 + '%');
          },
        });
        console.log('上传成功:', result.url);
      };
    </script>
  </head>
  <body>
    <input type="file" id="file" />
    <button id="upload">上传</button>
  </body>
</html>

多环境上传

支持同时上传到不同环境:

import { BeLinkCOS } from '@be-link/cos';

// 创建开发环境上传器
const devUploader = new BeLinkCOS({ mode: 'development' });

// 创建生产环境上传器
const prodUploader = new BeLinkCOS({ mode: 'production' });

// 同时上传到不同环境
await Promise.all([devUploader.uploadFile(file), prodUploader.uploadFile(file)]);

特定项目桶配置

某些项目需要使用专用的存储桶,通过 projectName 参数指定:

浏览器端使用

import { BeLinkCOS } from '@be-link/cos';

// be-link-live-h5 项目使用专用桶
const uploader = new BeLinkCOS({
  mode: 'production',
  projectName: 'be-link-live-h5',
});

// 文件会自动上传到专用桶:
// - 桶名称: release-belink-1304510571
// - 桶地址: release-belink-1304510571.cos.ap-shanghai.myqcloud.com
// - 地域: ap-shanghai
await uploader.uploadFile(file);

CLI 命令行使用

# be-link-live-h5 项目上传
node_modules/.bin/cos production --project be-link-live-h5

# 或使用简写
node_modules/.bin/cos production -p be-link-live-h5

# 其他项目使用默认桶
node_modules/.bin/cos production

当前支持的特定项目配置

| 项目名称 | 环境 | 桶名称 | 地域 | | ----------------- | ---------- | --------------------------- | ----------- | | be-link-live-h5 | production | release-belink-1304510571 | ap-shanghai |


API 文档

new BeLinkCOS(config?)

创建 COS 上传器实例

支持两种使用方式:

  1. 立即初始化:传入配置对象,构造函数中自动调用 init()
  2. 延迟初始化:不传配置,稍后调用 init() 方法(支持异步配置)

参数:

  • config.mode - 必填 环境模式:'development' | 'test' | 'production'
  • config.projectName - 可选,项目标识,用于特定项目的专用桶配置(如 'be-link-live-h5'
  • config.headers - 可选,自定义请求头
  • config.ScopeLimit - 可选,是否限制临时密钥范围(默认 false
  • config.debug - 可选,是否开启调试模式(默认 false

示例:

// 方式一:立即初始化
const uploader = new BeLinkCOS({ mode: 'production' });

// 方式二:延迟初始化(支持异步配置)
const uploader = new BeLinkCOS();
const config = await fetchConfig(); // 从服务器获取配置
uploader.init({ mode: config.mode });

// 带自定义请求头
const uploader = new BeLinkCOS({
  mode: 'production',
  headers: { 'x-custom': 'value' },
  debug: true, // 开启调试日志
});

uploader.init(config)

初始化 COS 实例(用于延迟初始化场景)

参数:

  • config.mode - 必填 环境模式
  • config.headers - 可选,自定义请求头
  • config.ScopeLimit - 可选,是否限制临时密钥范围
  • config.debug - 可选,是否开启调试模式

示例:

const uploader = new BeLinkCOS();
uploader.init({ mode: 'production' });

uploader.uploadFile(file, config)

上传文件到 COS

参数:

  • file - 要上传的文件对象
  • config.onProgressCallback - 可选,进度回调函数
  • config.Headers - 可选,自定义请求头

返回:

{
  url: string,        // 文件访问 URL
  Location: string,   // 文件位置
  ETag: string,       // 文件 ETag
  statusCode: number, // HTTP 状态码
  headers: {}         // 响应头
}

示例:

const result = await uploader.uploadFile(file, {
  onProgressCallback: (data) => {
    console.log('进度:', data.percent * 100 + '%');
  },
});
console.log('上传成功:', result.url);

uploader.getSourceUrl(file)

获取文件上传后的 URL(不执行实际上传)

const url = await uploader.getSourceUrl(file);

uploader.createFileMd5(file, chunkSize?)

计算文件 MD5 哈希值

const md5 = await uploader.createFileMd5(file, 2 * 1024 * 1024); // 默认 2MB 分片

uploader.getConfig()

获取当前实例的配置信息

const config = uploader.getConfig();
console.log(config); // { mode: 'production', headers: {}, scopeLimit: false }

uploader.destroy()

销毁实例,清理资源

uploader.destroy();

环境配置

| 环境 | Bucket | 区域 | | ----------- | ------------------ | ---------- | | development | dev-1304510571 | ap-nanjing | | test | dev-1304510571 | ap-nanjing | | production | release-1304510571 | ap-nanjing |


TypeScript 类型

import { BeLinkCOS } from '@be-link/cos';
import type {
  EnvMode, // 'development' | 'test' | 'production'
  BucketConfig, // Bucket 配置
  InitConfig, // 初始化配置
  UploadConfig, // 上传配置
  UploadResult, // 上传结果
} from '@be-link/cos';

常见问题

1. 两种初始化方式有什么区别?

立即初始化:配置在编译时已知,直接传入构造函数

const uploader = new BeLinkCOS({ mode: 'production' });

延迟初始化:配置需要异步获取(如从服务器获取),先创建实例再初始化

const uploader = new BeLinkCOS();

// 稍后(可以是异步)
const config = await fetchConfigFromServer();
uploader.init({ mode: config.mode });

设计理念: 参考了 BeLinkLogDot 的设计模式,支持更灵活的配置方式。

2. 为什么 mode 必须传?

设计理念:强制显式配置,避免默认值陷阱

如果提供默认值(如 development),很容易出现以下问题:

  • 开发者忘记修改配置,生产环境代码误传到开发环境
  • 或者开发环境配置被复制到生产,导致测试数据污染生产环境

因此,我们要求必须显式指定环境:

// ✅ 正确:明确指定环境,不会搞错
const uploader = new BeLinkCOS({ mode: 'production' });

// ✅ 也可以延迟初始化
const uploader = new BeLinkCOS();
uploader.init({ mode: 'production' });

这样设计更安全,用户必须思考"我要上传到哪个环境"。

3. 上传失败怎么办?

检查:

  • mode 参数是否正确
  • 实例是否已初始化(调用了 init() 或构造函数传入了配置)
  • 网络是否正常
  • 浏览器控制台是否有错误信息(可以开启 debug: true 查看详细日志)

4. 文件存储路径是什么?

文件会自动存储到:/beLinkAllSource/static/{文件类型}/{文件名}_{时间戳}.{扩展名}

例如:/beLinkAllSource/static/image/avatar_1699999999999.png

5. 支持哪些文件类型?

支持所有文件类型,会根据文件的 MIME 类型自动分类存储(image、video、audio、application、text、other)。

6. 如何切换环境?

创建不同环境的实例:

const devUploader = new BeLinkCOS({ mode: 'development' });
const prodUploader = new BeLinkCOS({ mode: 'production' });

安全说明

✅ 本工具使用临时密钥方式,通过云函数动态获取授权
✅ 不会在客户端暴露永久密钥,安全可靠
✅ 临时密钥具有时效性,过期自动失效


许可证

ISC

维护者

zhuifeng [email protected]