Skip to content

OSS 文件上传配置

Upload 和 UploadCard 组件需要配置 OSS API 才能正常工作。

配置 OSS API

typescript
import { setupPageTemplate } from "vue-admin-kit";
import { uploadOSS, deleteOSS } from "@/api/system/oss";

setupPageTemplate({
  dependencies: {
    oss: {
      // 上传文件
      uploadOSS: async (file: File | FormData) => {
        const formData =
          file instanceof FormData
            ? file
            : (() => {
                const fd = new FormData();
                fd.append("files", file);
                return fd;
              })();
        const res = await uploadOSS(formData);
        // 返回格式必须包含 url, fileName, ossId
        return {
          url: res.data?.url || "",
          fileName: res.data?.fileName || res.data?.originalName || "",
          ossId: res.data?.ossId || "",
        };
      },
      // 删除文件
      deleteOSS: async (ossId: string | number) => {
        const res = await deleteOSS(ossId);
        return { code: res.code, msg: res.msg };
      },
    },
  },
});

OSS API 接口类型

typescript
interface OssApi {
  /**
   * 上传文件到 OSS
   * @param file 文件对象或 FormData
   * @returns Promise<{ url: string; fileName: string; ossId?: string }>
   */
  uploadOSS(file: File | FormData): Promise<{
    url: string;
    fileName: string;
    ossId?: string | number;
  }>;

  /**
   * 删除 OSS 文件
   * @param ossId 文件 ID
   * @returns Promise<{ code: number; msg?: string }>
   */
  deleteOSS(ossId: string | number): Promise<{
    code: number;
    msg?: string;
  }>;
}

Upload 组件使用示例

typescript
const formConfig = [
  {
    type: "upload",
    prop: "attachments",
    label: "附件",
    uploadConfigList: [
      {
        prop: "files",
        label: "上传文件",
        bizType: "attachment", // 业务类型,会传给后端
        limit: 5, // 最大文件数
        accept: ".pdf,.doc,.docx,.xls,.xlsx", // 允许的文件类型
      },
    ],
  },
  {
    type: "uploadCard",
    prop: "images",
    label: "图片",
    uploadConfigList: [
      {
        prop: "coverImage",
        label: "封面图",
        bizType: "cover",
        limit: 1,
        accept: ".jpg,.jpeg,.png,.gif",
      },
    ],
  },
];

uploadConfigList 配置项

属性类型说明
propstring字段名
labelstring标签
bizTypestring业务类型,会传给后端
limitnumber最大文件数
acceptstring允许的文件类型
requiredboolean是否必填

Released under the MIT License.