upload.js
2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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();