forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.ts
More file actions
746 lines (661 loc) · 23.2 KB
/
Copy pathfile.ts
File metadata and controls
746 lines (661 loc) · 23.2 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
import type { S3ClientConfig } from '@aws-sdk/client-s3'
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import fetch from '@md/shared/utils/fetch'
import * as tokenTools from '@md/shared/utils/tokenTools'
import { base64encode, safe64, utf16to8 } from '@md/shared/utils/tokenTools'
import Buffer from 'buffer-from'
import CryptoJS from 'crypto-js'
import * as qiniu from 'qiniu-js'
import { v4 as uuidv4 } from 'uuid'
import { uploadDefaultImage } from '@/services/upload/client'
import { store } from './storage'
/**
* Safely parse JSON string, returns parsed result or throws a descriptive error
*/
function safeJsonParse<T>(str: string | null | undefined, context: string = `configuration`): T {
if (!str) {
throw new Error(`${context} is missing or empty`)
}
try {
return JSON.parse(str) as T
}
catch {
throw new Error(`Failed to parse ${context}: corrupted data`)
}
}
async function getConfig(platform: string) {
const customConfig = await store.getJSON<any>(`${platform}Config`, {}) || {}
const repoUrl = customConfig.repo
.replace(`https://${platform}.com/`, ``)
.replace(`http://${platform}.com/`, ``)
.replace(`${platform}.com/`, ``)
.split(`/`)
return {
username: repoUrl[0],
repo: repoUrl[1],
branch: customConfig.branch || `master`,
accessToken: customConfig.accessToken,
useCDN: customConfig.useCDN ?? false,
}
}
/**
* 获取 `年/月/日` 形式的目录
* @returns string
*/
function getDir() {
const date = new Date()
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, `0`)
const day = date.getDate().toString().padStart(2, `0`)
return `${year}/${month}/${day}`
}
/**
* 根据文件名获取它以 `时间戳+uuid` 的形式
* @param {string} filename 文件名
* @returns {string} `时间戳+uuid`
*/
function getDateFilename(filename: string) {
const currentTimestamp = Date.now()
// 获取最后一个点号后的内容作为文件扩展名
const fileSuffix = filename.split(`.`).pop()
return `${currentTimestamp}-${uuidv4()}.${fileSuffix}`
}
async function defaultImageUpload(_content: string, file: File): Promise<string> {
return await uploadDefaultImage(file)
}
// -----------------------------------------------------------------------
// GitHub File Upload
// -----------------------------------------------------------------------
async function ghFileUpload(content: string, filename: string) {
const { username, repo, branch, accessToken, useCDN } = await getConfig(`github`)
const dir = getDir()
const url = `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`
const dateFilename = getDateFilename(filename)
const res = await fetch<{ content: {
download_url: string
} }, {
content: {
download_url: string
}
data?: {
content: {
download_url: string
}
}
}>({
url: url + dateFilename,
method: `put`,
headers: {
Authorization: `token ${accessToken}`,
},
data: {
content,
branch,
message: `Upload by ${window.location.href}`,
},
})
const githubResourceUrl = `raw.githubusercontent.com/${username}/${repo}/${branch}/`
const cdnResourceUrl = `fastly.jsdelivr.net/gh/${username}/${repo}@${branch}/`
res.content = res.data?.content || res.content
const shouldUseCDN = useCDN
return shouldUseCDN
? res.content.download_url.replace(githubResourceUrl, cdnResourceUrl)
: res.content.download_url
}
// -----------------------------------------------------------------------
// Qiniu File Upload
// -----------------------------------------------------------------------
function getQiniuToken(accessKey: string, secretKey: string, putPolicy: {
scope: string
deadline: number
}) {
const policy = JSON.stringify(putPolicy)
const encoded = base64encode(utf16to8(policy))
const hash = CryptoJS.HmacSHA1(encoded, secretKey)
const encodedSigned = hash.toString(CryptoJS.enc.Base64)
return `${accessKey}:${safe64(encodedSigned)}:${encoded}`
}
async function qiniuUpload(file: File) {
const configStr = await store.get(`qiniuConfig`)
const { accessKey, secretKey, bucket, region, path, domain } = safeJsonParse<{ accessKey: string, secretKey: string, bucket: string, region?: string, path: string, domain: string }>(configStr, `qiniu config`)
const token = getQiniuToken(accessKey, secretKey, {
scope: bucket,
deadline: Math.trunc(Date.now() / 1000) + 3600,
})
const dir = path ? `${path}/` : ``
const dateFilename = dir + getDateFilename(file.name)
const observable = qiniu.upload(file, dateFilename, token, {}, { region: region as any })
return new Promise<string>((resolve, reject) => {
observable.subscribe({
next: () => {},
error: (err) => {
reject(err.message)
},
complete: (result) => {
resolve(`${domain}/${result.key}`)
},
})
})
}
// -----------------------------------------------------------------------
// AliOSS File Upload
// -----------------------------------------------------------------------
async function aliOSSFileUpload(file: File) {
const dateFilename = getDateFilename(file.name)
const config = await store.getJSON(`aliOSSConfig`, { region: ``, bucket: ``, accessKeyId: ``, accessKeySecret: ``, useSSL: true, cdnHost: ``, path: `` })
const { region, bucket, accessKeyId, accessKeySecret, useSSL, cdnHost, path }
= config || { region: ``, bucket: ``, accessKeyId: ``, accessKeySecret: ``, useSSL: true, cdnHost: ``, path: `` }
// Transform aliOSSConfig to s3Config format
// Aliyun OSS endpoints follow pattern: https://<bucket>.<region>.aliyuncs.com or https://<region>.aliyuncs.com
const secure = useSSL === undefined || useSSL
const protocol = secure ? `https` : `http`
const endpoint = `${protocol}://${region}.aliyuncs.com`
const clientConfig: S3ClientConfig = {
region,
credentials: {
accessKeyId,
secretAccessKey: accessKeySecret,
},
endpoint,
forcePathStyle: false,
}
const s3Client = new S3Client(clientConfig)
const dir = path ? `${path}/` : ``
const key = dir + dateFilename
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
ContentType: file.type,
})
try {
const presignedUrl = await getSignedUrl(s3Client, command, { expiresIn: 300 })
const response = await window.fetch(presignedUrl, {
method: `PUT`,
headers: {
'Content-Type': file.type,
},
body: file,
})
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
if (cdnHost) {
const host = cdnHost.endsWith('/') ? cdnHost.slice(0, -1) : cdnHost
return `${host}/${key}`
}
// Default OSS URL format
return `${protocol}://${bucket}.${region}.aliyuncs.com/${key}`
}
catch (e) {
return Promise.reject(e)
}
}
// -----------------------------------------------------------------------
// TxCOS File Upload
// -----------------------------------------------------------------------
async function txCOSFileUpload(file: File) {
const dateFilename = getDateFilename(file.name)
const configStr = await store.get(`txCOSConfig`)
const { secretId, secretKey, bucket, region, path, cdnHost } = safeJsonParse<{ secretId: string, secretKey: string, bucket: string, region: string, path: string, cdnHost: string }>(configStr, `txCOS config`)
// Transform txCOSConfig to S3 format
// Tencent Cloud COS S3 endpoint: https://cos.<Region>.myqcloud.com
const endpoint = `https://cos.${region}.myqcloud.com`
const clientConfig: S3ClientConfig = {
region,
credentials: {
accessKeyId: secretId,
secretAccessKey: secretKey,
},
endpoint,
forcePathStyle: false,
}
const s3Client = new S3Client(clientConfig)
const dir = path ? `${path}/` : ``
const key = dir + dateFilename
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
ContentType: file.type,
})
try {
const presignedUrl = await getSignedUrl(s3Client, command, { expiresIn: 300 })
const response = await window.fetch(presignedUrl, {
method: `PUT`,
headers: {
'Content-Type': file.type,
},
body: file,
})
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
if (cdnHost) {
return path === ``
? `${cdnHost}/${dateFilename}`
: `${cdnHost}/${path}/${dateFilename}`
}
// Default COS URL: https://<BucketName-APPID>.cos.<Region>.myqcloud.com/<Key>
// The 'bucket' param in COS usually is 'name-appid', if not, user might need to check.
// However, for S3 client, we just use the bucket name provided.
return `https://${bucket}.cos.${region}.myqcloud.com/${key}`
}
catch (e) {
return Promise.reject(e)
}
}
// -----------------------------------------------------------------------
// Minio File Upload
// -----------------------------------------------------------------------
async function minioFileUpload(file: File) {
const dateFilename = getDateFilename(file.name)
const configStr = await store.get(`minioConfig`)
const { endpoint, port, useSSL, bucket, accessKey, secretKey } = safeJsonParse<{ endpoint: string, port: string, useSSL: boolean, bucket: string, accessKey: string, secretKey: string }>(configStr, `minio config`)
const s3Client = new S3Client({
endpoint: `${useSSL ? `https` : `http`}://${endpoint}${port ? `:${port}` : ``}`,
credentials: {
accessKeyId: accessKey,
secretAccessKey: secretKey,
},
region: `auto`,
forcePathStyle: true,
})
const command = new PutObjectCommand({
Bucket: bucket,
Key: dateFilename,
ContentType: file.type,
})
const presignedUrl = await getSignedUrl(s3Client, command, { expiresIn: 300 })
await fetch(presignedUrl, {
method: `PUT`,
headers: {
'Content-Type': file.type,
},
data: file,
})
return `${useSSL ? `https` : `http`}://${endpoint}${port ? `:${port}` : ``}/${bucket}/${dateFilename}`
}
// -----------------------------------------------------------------------
// S3 File Upload
// -----------------------------------------------------------------------
const PROTOCOL_REGEX = /^https?:\/\//
async function s3Upload(file: File) {
const dateFilename = getDateFilename(file.name)
const config = await store.getJSON(`s3Config`, {
endpoint: ``,
region: ``,
bucket: ``,
accessKeyId: ``,
accessKeySecret: ``,
path: ``,
cdnHost: ``,
pathStyle: false,
})
const { endpoint, region, bucket, accessKeyId, accessKeySecret, path, cdnHost, pathStyle } = config
const resolvedEndpoint = endpoint
? endpoint.startsWith('http') ? endpoint : `https://${endpoint}`
: undefined
const clientConfig: S3ClientConfig = {
region,
credentials: {
accessKeyId,
secretAccessKey: accessKeySecret,
},
forcePathStyle: pathStyle,
endpoint: resolvedEndpoint,
}
const s3Client = new S3Client(clientConfig)
const dir = path ? `${path}/` : ``
const key = dir + dateFilename
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
ContentType: file.type,
})
const presignedUrl = await getSignedUrl(s3Client, command, { expiresIn: 300 })
const response = await window.fetch(presignedUrl, {
method: `PUT`,
headers: {
'Content-Type': file.type,
},
body: file,
})
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
if (cdnHost) {
const host = cdnHost.endsWith('/') ? cdnHost.slice(0, -1) : cdnHost
return `${host}/${key}`
}
if (endpoint && resolvedEndpoint) {
const proto = resolvedEndpoint.startsWith('https') ? 'https' : 'http'
const host = resolvedEndpoint.replace(PROTOCOL_REGEX, '')
if (pathStyle) {
return `${proto}://${host}/${bucket}/${key}`
}
else {
return `${proto}://${bucket}.${host}/${key}`
}
}
return `https://${bucket}.s3.${region}.amazonaws.com/${key}`
}
// -----------------------------------------------------------------------
// mp File Upload
// -----------------------------------------------------------------------
interface MpResponse {
access_token: string
expires_in: number
errcode: number
errmsg: string
}
async function getMpToken(appID: string, appsecret: string, proxyOrigin?: string) {
const data = await store.get(`mpToken:${appID}`)
if (data) {
try {
const token = JSON.parse(data)
if (token.expire && token.expire > Date.now()) {
return token.access_token
}
}
catch {
// Corrupted token data, ignore and request a new one
}
}
const requestOptions = {
method: `POST`,
data: {
grant_type: `client_credential`,
appid: appID,
secret: appsecret,
},
}
let url = `https://api.weixin.qq.com/cgi-bin/stable_token`
if (proxyOrigin) {
url = `${proxyOrigin}/cgi-bin/stable_token`
}
const res = await fetch<any, MpResponse>(url, requestOptions)
if (res.access_token) {
const tokenInfo = {
...res,
expire: Date.now() + res.expires_in * 1000,
}
await store.setJSON(`mpToken:${appID}`, tokenInfo)
return res.access_token
}
return ``
}
// Cloudflare Workers 环境
const isCfWorkers = import.meta.env.CF_WORKERS === `1`
async function mpFileUpload(file: File) {
const configStr = await store.get(`mpConfig`)
let { appID, appsecret, proxyOrigin } = safeJsonParse<{ appID: string, appsecret: string, proxyOrigin?: string }>(configStr, `mp config`)
// 未填写代理域名且是 Cloudflare Workers 环境时,使用当前域名作为代理域名
if (!proxyOrigin && isCfWorkers) {
proxyOrigin = window.location.origin
}
const access_token = await getMpToken(appID, appsecret, proxyOrigin)
if (!access_token) {
throw new Error(`获取 access_token 失败`)
}
const formdata = new FormData()
formdata.append(`media`, file, file.name)
const requestOptions = {
method: `POST`,
data: formdata,
}
let url = `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${access_token}&type=image`
const fileSizeInMB = file.size / (1024 * 1024)
const fileType = file.type.toLowerCase()
if (fileSizeInMB < 1 && (fileType === `image/jpeg` || fileType === `image/png`)) {
url = `https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=${access_token}`
}
if (proxyOrigin) {
url = url.replace(`https://api.weixin.qq.com`, proxyOrigin)
}
const res = await fetch<any, { url: string }>(url, requestOptions)
if (!res.url) {
throw new Error(`上传失败,未获取到URL`)
}
let imageUrl = res.url
if (proxyOrigin && window.location.href.startsWith(`http`)) {
imageUrl = `https://wsrv.nl?url=${encodeURIComponent(imageUrl)}`
}
return imageUrl
}
// -----------------------------------------------------------------------
// Cloudflare R2 File Upload
// -----------------------------------------------------------------------
async function r2Upload(file: File) {
const configStr = await store.get(`r2Config`)
const { accountId, accessKey, secretKey, bucket, path, domain } = safeJsonParse<{ accountId: string, accessKey: string, secretKey: string, bucket: string, path: string, domain: string }>(configStr, `r2 config`)
const dir = path ? `${path}/` : ``
const filename = dir + getDateFilename(file.name)
const client = new S3Client({ region: `auto`, endpoint: `https://${accountId}.r2.cloudflarestorage.com`, credentials: { accessKeyId: accessKey, secretAccessKey: secretKey } })
const signedUrl = await getSignedUrl(
client,
new PutObjectCommand({ Bucket: bucket, Key: filename, ContentType: file.type }),
{ expiresIn: 300 },
)
await fetch(signedUrl, {
method: `PUT`,
headers: {
'Content-Type': file.type,
},
data: file,
})
return `${domain}/${filename}`
}
// -----------------------------------------------------------------------
// Upyun File Upload
// -----------------------------------------------------------------------
async function upyunUpload(file: File) {
const configStr = await store.get(`upyunConfig`)
const { bucket, operator, password, path, domain } = safeJsonParse<{ bucket: string, operator: string, password: string, path: string, domain: string }>(configStr, `upyun config`)
const filename = `${path}/${getDateFilename(file.name)}`
const uri = `/${bucket}/${filename}`
const arrayBuffer = await file.arrayBuffer()
const date = new Date().toUTCString()
const method = `PUT`
const signStr = [method, uri, date].join(`&`)
const passwordMd5 = CryptoJS.MD5(password).toString()
const signature = CryptoJS.HmacSHA1(signStr, passwordMd5).toString(CryptoJS.enc.Base64)
const authorization = `UPYUN ${operator}:${signature}`
const url = `https://v0.api.upyun.com${uri}`
const res = await window.fetch(url, {
method: `PUT`,
headers: {
'Authorization': authorization,
'X-Date': date,
'Content-Type': file.type,
},
body: arrayBuffer,
})
if (!res.ok) {
throw new Error(`上传失败: ${await res.text()}`)
}
return `${domain}/${filename}`
}
// -----------------------------------------------------------------------
// Telegram File Upload
// -----------------------------------------------------------------------
async function telegramUpload(file: File): Promise<string> {
const config = await store.getJSON(`telegramConfig`, { token: ``, chatId: `` })
const { token, chatId } = config || { token: ``, chatId: `` }
// 1. sendPhoto
const form = new FormData()
form.append(`chat_id`, chatId)
form.append(`photo`, file, file.name)
const sendRes = await fetch<any, {
ok: boolean
result: {
photo: { file_id: string }[]
}
}>({
url: `https://api.telegram.org/bot${token}/sendPhoto`,
method: `POST`,
data: form,
})
if (!sendRes.ok || !sendRes.result.photo.length) {
throw new Error(`Telegram sendPhoto 失败`)
}
// 取最大的分辨率那张图
const fileId = sendRes.result.photo[sendRes.result.photo.length - 1].file_id
// 2. getFile
const fileRes = await fetch<any, {
ok: boolean
result: { file_path: string }
}>({
url: `https://api.telegram.org/bot${token}/getFile?file_id=${fileId}`,
method: `GET`,
})
if (!fileRes.ok) {
throw new Error(`Telegram getFile 失败`)
}
const filePath = fileRes.result.file_path
// 3. 拼出下载地址
return `https://api.telegram.org/file/bot${token}/${filePath}`
}
// -----------------------------------------------------------------------
// Cloudinary File Upload
// -----------------------------------------------------------------------
/**
* cloudinaryConfig 配置示例:
* {
* "cloudName": "demo",
* "apiKey": "1234567890",
* "apiSecret": "abcdefg1234567890", // 可选:若未填写则走 unsigned preset
* "uploadPreset": "unsigned_preset", // 可选:有 apiSecret 时可省略
* "folder": "blog/image", // 可选:Cloudinary 目录,留空则根路径
* "domain": "https://cdn.example.com" // 可选:自定义访问域名 / CDN 域名
* }
*/
async function cloudinaryUpload(file: File): Promise<string> {
const config = await store.getJSON(`cloudinaryConfig`, { cloudName: ``, apiKey: ``, apiSecret: ``, uploadPreset: ``, folder: ``, domain: `` })
const {
cloudName,
apiKey,
apiSecret,
uploadPreset,
folder = ``,
domain,
} = config || { cloudName: ``, apiKey: ``, apiSecret: ``, uploadPreset: ``, folder: ``, domain: `` }
if (!cloudName || !apiKey)
throw new Error(`Cloudinary 配置缺少 cloudName / apiKey`)
const timestamp = Math.floor(Date.now() / 1000) // Cloudinary 要求秒级时间戳
const formData = new FormData()
formData.append(`file`, file)
formData.append(`api_key`, apiKey)
formData.append(`timestamp`, `${timestamp}`)
// ---------- 1) 需要签名的场景 ----------
if (apiSecret) {
// 参与签名的字段需按字典序排列并拼接成 a=b&c=d… 的格式
const params: string[] = []
if (folder)
params.push(`folder=${folder}`)
if (uploadPreset)
params.push(`upload_preset=${uploadPreset}`)
params.push(`timestamp=${timestamp}`)
const signatureBase = params.sort().join(`&`)
const signature = CryptoJS.SHA1(signatureBase + apiSecret).toString()
formData.append(`signature`, signature)
}
// ---------- 2) unsigned preset ----------
else if (uploadPreset) {
formData.append(`upload_preset`, uploadPreset)
}
else {
throw new Error(`未配置 apiSecret 时必须提供 uploadPreset`)
}
if (folder)
formData.append(`folder`, folder)
const uploadUrl = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`
const res = await fetch<any, { secure_url?: string, url?: string }>(uploadUrl, {
method: `POST`,
data: formData,
})
const originUrl = res.secure_url || res.url
if (!originUrl)
throw new Error(`Cloudinary 返回缺少 url 字段`)
// 如果配置了自定义域名,则把 host 换掉
if (domain) {
const { pathname, search } = new URL(originUrl)
return `${domain}${pathname}${search}`
}
return originUrl
}
// -----------------------------------------------------------------------
// formCustom File Upload
// -----------------------------------------------------------------------
async function formCustomUpload(content: string, file: File) {
const customConfig = await store.get(`formCustomConfig`)
const str = `
async (CUSTOM_ARG) => {
${customConfig}
}
`
return new Promise<string>((resolve, reject) => {
const exportObj = {
content, // 待上传图片的 base64
file, // 待上传图片的 file 对象
util: {
axios: fetch, // axios 实例
CryptoJS, // 加密库
// OSS, // OSS references removed
// COS, // COS references removed
Buffer, // buffer-from
uuidv4, // uuid
qiniu, // qiniu-js
tokenTools, // 一些编码转换函数
getDir, // 获取 年/月/日 形式的目录
getDateFilename, // 根据文件名获取它以 时间戳+uuid 的形式
S3: {
S3Client,
PutObjectCommand,
getSignedUrl,
},
},
okCb: resolve, // 重要: 上传成功后给此回调传 url 即可
errCb: reject, // 上传失败调用的函数
}
// Use Function constructor instead of eval
// eslint-disable-next-line no-new-func
const fn = new Function(`return (${str})`)()
fn(exportObj).catch((err: unknown) => {
reject(err)
})
})
}
export async function fileUpload(content: string, file: File) {
const imgHost = await store.get(`imgHost`)
if (!imgHost) {
await store.set(`imgHost`, `default`)
}
switch (imgHost) {
case `aliOSS`:
return aliOSSFileUpload(file)
case `minio`:
return minioFileUpload(file)
case `s3`:
return s3Upload(file)
case `txCOS`:
return txCOSFileUpload(file)
case `qiniu`:
return qiniuUpload(file)
case `github`:
return ghFileUpload(content, file.name)
case `mp`:
return mpFileUpload(file)
case `r2`:
return r2Upload(file)
case `upyun`:
return upyunUpload(file)
case `telegram`:
return telegramUpload(file)
case `cloudinary`:
return cloudinaryUpload(file)
case `formCustom`:
return formCustomUpload(content, file)
default:
return defaultImageUpload(content, file)
}
}