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

uniapp-oss-upload

v1.0.2

Published

一个专为 uni-app 设计的阿里云 OSS 文件直传模块,支持自定义表单数据、文件重命名、目录管理等功能。

Readme

Ali-OSS Upload 模块

一个专为 uni-app 设计的阿里云 OSS 文件直传模块,支持自定义表单数据、文件重命名、目录管理等功能。

功能特性

  • 简单易用:一行代码完成文件上传
  • 自动签名:自动生成 OSS 上传签名
  • 文件重命名:支持自定义文件名
  • 目录管理:支持文件分类存储
  • 自定义表单:支持传入自定义表单数据
  • 上传进度:实时监控上传进度
  • 类型安全:完整的 TypeScript 类型定义
  • 错误处理:完善的参数验证和错误提示

安装使用

npm i uniapp-oss-upload

1. 导入模块

import { ossUpload } from "uniapp-oss-upload";

2. 基础使用

// 最简单的使用方式
ossUpload({
  filePath: "/path/to/your/file.jpg",
  url: "oss-cn-hangzhou.aliyuncs.com",
  bucket: "your-bucket-name",
  OSSAccessKeyId: "your-access-key-id",
  OssAccesskeySercet: "your-access-key-secret",
})
  .then((result) => {
    console.log("上传成功,文件URL:", result.data);
  })
  .catch((err) => {
    console.error("上传失败:", err.data);
  })
  .finally(() => {
    uni.hideLoading();
  });

API 文档

OssUploadParams 接口

| 参数 | 类型 | 必填 | 说明 | | -------------------- | --------------------- | ---- | -------------------------------------------- | | filePath | string | ✅ | 本地文件路径 | | url | string | ✅ | OSS 域名(如:oss-cn-hangzhou.aliyuncs.com) | | bucket | string | ✅ | OSS 存储桶名称 | | OSSAccessKeyId | string | ✅ | OSS AccessKeyId | | OssAccesskeySercet | string | ✅ | OSS AccessKeySecret | | name | string | ❌ | 自定义文件名(不包含路径) | | dir | string | ❌ | 存储目录(如:'images/') | | customFormData | Record<string, any> | ❌ | 自定义表单数据 | | onProgress | function | ❌ | 上传进度回调函数 |

OssUploadResult 接口

| 字段 | 类型 | 说明 | | --------- | --------- | -------------------------------------- | | success | boolean | 上传是否成功 | | data | string | 成功时返回文件 URL,失败时返回错误信息 |

OssUploadProgress 接口

| 字段 | 类型 | 说明 | | -------------------------- | -------- | ---------------------------------- | | progress | number | 上传进度百分比(0-100) | | totalBytesSent | number | 已上传的数据长度,单位字节 | | totalBytesExpectedToSend | number | 预期需要上传的数据总长度,单位字节 |

使用示例

1. 基础文件上传

try {
  const result = await ossUpload({
    filePath: "/path/to/image.jpg",
    url: "oss-cn-hangzhou.aliyuncs.com",
    bucket: "my-bucket",
    OSSAccessKeyId: "LTAI5t...",
    OssAccesskeySercet: "your-secret-key",
  });

  if (result.success) {
    console.log("文件上传成功:", result.data);
  }
} catch (error) {
  console.error("上传失败:", error);
}

2. 自定义文件名和目录

const result = await ossUpload({
  filePath: "/path/to/photo.jpg",
  name: "avatar.jpg", // 自定义文件名
  dir: "users/avatars/", // 存储目录
  url: "oss-cn-hangzhou.aliyuncs.com",
  bucket: "my-bucket",
  OSSAccessKeyId: "LTAI5t...",
  OssAccesskeySercet: "your-secret-key",
});

3. 使用自定义表单数据

const result = await ossUpload({
  filePath: "/path/to/document.pdf",
  dir: "documents/",
  url: "oss-cn-hangzhou.aliyuncs.com",
  bucket: "my-bucket",
  OSSAccessKeyId: "LTAI5t...",
  OssAccesskeySercet: "your-secret-key",
  customFormData: {
    // 设置文件内容类型
    "x-oss-content-type": "application/pdf",
    // 设置缓存控制
    "x-oss-cache-control": "max-age=3600",
    // 添加自定义元数据
    "x-oss-meta-author": "John Doe",
    "x-oss-meta-description": "Important document",
    // 设置对象标签
    "x-oss-tagging": "category=document&type=pdf",
    // 设置存储类型
    "x-oss-storage-class": "Standard",
  },
});

4. 监控上传进度

const result = await ossUpload({
  filePath: "/path/to/large-file.mp4",
  dir: "videos/",
  url: "oss-cn-hangzhou.aliyuncs.com",
  bucket: "my-bucket",
  OSSAccessKeyId: "LTAI5t...",
  OssAccesskeySercet: "your-secret-key",
  // 上传进度回调
  onProgress: (progressData) => {
    console.log(`上传进度: ${progressData.progress}%`);
    console.log(`已上传: ${progressData.totalBytesSent} 字节`);
    console.log(`总大小: ${progressData.totalBytesExpectedToSend} 字节`);

    // 更新 UI 进度条
    // this.uploadProgress = progressData.progress;
  },
});

5. 在 Vue 组件中使用(带进度条)

<template>
  <view>
    <button @click="chooseAndUpload">选择并上传文件</button>

    <!-- 进度条 -->
    <view v-if="uploading" class="progress-container">
      <progress :percent="uploadProgress" show-info stroke-width="3" />
      <text>{{ uploadProgressText }}</text>
    </view>

    <view v-if="uploadResult">
      <text>上传结果:{{ uploadResult }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ossUpload } from "uniapp-oss-upload";

const uploadResult = ref("");
const uploading = ref(false);
const uploadProgress = ref(0);
const uploadProgressText = ref("");

const chooseAndUpload = async () => {
  try {
    // 选择文件
    const res = await uni.chooseImage({
      count: 1,
      sourceType: ["album", "camera"],
    });

    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      const filePath = res.tempFilePaths[0];

      uploading.value = true;
      uploadProgress.value = 0;

      // 上传文件
      const result = await ossUpload({
        filePath,
        dir: "uploads/",
        url: "oss-cn-hangzhou.aliyuncs.com",
        bucket: "my-bucket",
        OSSAccessKeyId: "LTAI5t...",
        OssAccesskeySercet: "your-secret-key",
        // 监听上传进度
        onProgress: (progressData) => {
          uploadProgress.value = progressData.progress;
          const sent = (progressData.totalBytesSent / 1024 / 1024).toFixed(2);
          const total = (
            progressData.totalBytesExpectedToSend /
            1024 /
            1024
          ).toFixed(2);
          uploadProgressText.value = `${sent}MB / ${total}MB`;
        },
      });

      uploading.value = false;

      if (result.success) {
        uploadResult.value = `上传成功:${result.data}`;
      } else {
        uploadResult.value = `上传失败:${result.data}`;
      }
    }
  } catch (error) {
    uploading.value = false;
    uploadResult.value = `上传失败:${error}`;
  }
};
</script>

<style scoped>
.progress-container {
  margin: 20px 0;
  padding: 10px;
}
</style>

支持的 OSS 自定义字段

通过 customFormData 参数,你可以设置以下 OSS 支持的字段:

内容类型和编码

  • x-oss-content-type: 设置文件 MIME 类型
  • x-oss-content-encoding: 设置内容编码
  • x-oss-content-disposition: 设置下载时的文件名

缓存控制

  • x-oss-cache-control: 设置缓存控制策略
  • x-oss-expires: 设置过期时间

元数据

  • x-oss-meta-*: 自定义元数据(如:x-oss-meta-authorx-oss-meta-description

对象标签

  • x-oss-tagging: 设置对象标签(格式:key1=value1&key2=value2

存储和加密

  • x-oss-storage-class: 存储类型(Standard、IA、Archive)
  • x-oss-server-side-encryption: 服务端加密
  • x-oss-server-side-encryption-key-id: 加密密钥 ID

访问控制

  • x-oss-object-acl: 对象访问权限(private、public-read、public-read-write)

错误处理

模块会进行以下参数验证:

  • 文件路径不能为空
  • OSS URL 不能为空
  • OSS Bucket 不能为空
  • OSS AccessKeyId 不能为空
  • OSS AccessKeySecret 不能为空
try {
  const result = await ossUpload({
    // ... 参数
  });

  if (result.success) {
    // 处理成功情况
    console.log("文件URL:", result.data);
  } else {
    // 处理失败情况
    console.error("上传失败:", result.data);
  }
} catch (error) {
  // 处理异常情况
  console.error("发生异常:", error);
}

注意事项

  1. 安全性:请勿在前端代码中硬编码 AccessKey 和 Secret,建议通过后端接口获取临时凭证
  2. 文件大小:默认限制文件大小为 1GB,如需修改请调整 policyText 中的 content-length-range
  3. 目录格式:目录参数应以 / 结尾,如 'images/'
  4. URL 格式:支持完整 URL 和域名两种格式
  5. 文件名:如果不指定 name 参数,系统会自动生成随机文件名

技术实现

  • 使用 HMAC-SHA1 算法生成签名
  • 支持 Base64 编码
  • 兼容 uni-app 的 uni.uploadFile API
  • 完整的 TypeScript 类型支持

开发指南

本地开发

# 克隆项目
git clone <your-repo-url>

# 安装依赖
npm install

# 构建项目
npm run build

发布到 npm

# 登录 npm
npm login

# 发布(会自动执行 prepublishOnly 钩子进行构建)
npm publish

项目结构

uniapp-oss-upload/
├── src/                # 源代码目录
│   ├── index.ts       # 主入口文件
│   ├── base64.ts      # Base64 编码
│   ├── crypto.ts      # 加密工具
│   ├── hmac.ts        # HMAC 实现
│   ├── sha1.ts        # SHA1 实现
│   └── types.d.ts     # uni-app 类型声明
├── dist/              # 编译输出目录(自动生成)
├── tsconfig.json      # TypeScript 配置
├── package.json       # 包配置
└── README.md          # 文档

许可证

MIT License