upload.js 2.37 KB
import { OSS_CONFIG } from "@/config/oss.ts";
import GlOssApi from "glsk-oss-jssdk";

let ossApi = null;

function getOssApi() {
    if (!ossApi) ossApi = new GlOssApi();
    return ossApi;
}

/**
 * 使用 glsk-oss-jssdk 分片上传到 OSS。
 *
 * @param {File} file
 * @param {{
 *  bucketName?: string,
 *  dir?: string,
 *  custAttrObj?: Record<string, any>,
 *  partSizeKB?: number,
 *  maxRetries?: number
 * }} [options]
 * @returns {Promise<any>} SDK 返回结果(含 aliyunAddress/attachment 等字段)
 */
export function uploadFile(file, options = {}) {
    if (!file) return Promise.reject(new Error("file 不能为空"));

    const api = getOssApi();
    const bucketName = options.bucketName ?? OSS_CONFIG.BUCKET_NAME;
    const dir = options.dir ?? OSS_CONFIG.FOLDER;
    const custAttrObj = options.custAttrObj ?? {
        systemSource: OSS_CONFIG.SYSTEM_SOURCE,
    };
    const partSizeKB = options.partSizeKB ?? 500;
    const maxRetries = options.maxRetries ?? 3;

    return new Promise((resolve, reject) => {
        api.multipartUpload(
            file,
            (res) => resolve(res),
            (err) => reject(err),
            bucketName,
            dir,
            custAttrObj,
            {},
            partSizeKB,
            maxRetries,
        );
    });
}

/**
 * 批量上传
 * @param {File[]} files
 * @param {Parameters<typeof uploadFile>[1]} [options]
 */
const IMAGE_EXT = /\.(jpe?g|png|gif|webp|bmp|svg|ico|heic|heif)$/i;
const VIDEO_EXT = /\.(mp4|webm|ogg|mov|mpe?g|avi|wmv|flv|mkv)$/i;

/** 是否为图片(MIME 优先;无 MIME 时按扩展名兜底,常见于部分移动端) */
export function isLikelyImageFile(file) {
    if (!file) return false;
    const t = (file.type || "").toLowerCase();
    if (t.startsWith("image/")) return true;
    if (!t && IMAGE_EXT.test(file.name || "")) return true;
    return false;
}

/** 是否为视频 */
export function isLikelyVideoFile(file) {
    if (!file) return false;
    const t = (file.type || "").toLowerCase();
    if (t.startsWith("video/")) return true;
    if (!t && VIDEO_EXT.test(file.name || "")) return true;
    return false;
}


// 将图片进行格式转换。
async function format() {
    try {
        const result = await ossApi.get("example.jpg", "./example-format.jpg", {
            process: "image/format,png",
        });
    } catch (e) {
        console.log(e);
    }
}

format();