Skip to content

Commit 0ba2fb2

Browse files
committed
fix: 临时代码
1 parent 44284c2 commit 0ba2fb2

2 files changed

Lines changed: 50 additions & 3 deletions

File tree

frontend/src/hooks/useCode.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import axios from 'axios'
44

55
import { HOST } from '@/utils/env'
66
import { LANG_MAP } from '@/utils/option'
7-
import { isBinaryContent } from '@/utils/file'
7+
import { getEncodeValue, isBinaryContent } from '@/utils/file'
88

99
import { useOpenStore } from '@/store/open'
1010

@@ -58,9 +58,12 @@ export default function useCode(option: OptionModel) {
5858
code.byte = headers['x-size'] ? Number(headers['x-size']) : undefined
5959
code.date = headers['x-update-date'] ? dayjs(headers['x-update-date']) : undefined
6060

61+
const info = await getEncodeValue(data)
62+
6163
code.blob = data
6264
code.path = path
63-
code.org = code.value = await data.text()
65+
code.encode = info.encode
66+
code.org = code.value = info.value
6467

6568
const filename = path.split('/').pop() || ''
6669

frontend/src/utils/file.ts

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import * as iconv from 'iconv-lite'
2+
13
import { HOST } from '@/utils/env'
4+
import { ENCODING_OPTIONS } from '@/utils/option'
25

36
export const getFileName = (v: string) => v.split('/').pop() || ''
47

@@ -42,7 +45,48 @@ export const getKey = (path: string) =>
4245
.join('-')
4346
.replace(/\./g, '_')
4447

45-
export async function isBinaryContent(blob: Blob) {
48+
export const getEncodeValue = async (blob: Blob) => {
49+
const result = { encode: '', value: '' }
50+
51+
const buffer = new Uint8Array(await blob.arrayBuffer())
52+
53+
if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
54+
result.encode = 'utf8'
55+
} else if (buffer[0] === 0xfe && buffer[1] === 0xff) {
56+
result.encode = 'utf16be'
57+
} else if (buffer[0] === 0xff && buffer[1] === 0xfe) {
58+
result.encode = 'utf16le'
59+
}
60+
61+
if (!result.encode) {
62+
for (const item of ENCODING_OPTIONS) {
63+
try {
64+
const text = iconv.decode(buffer, item.value)
65+
const sum = text.length
66+
const err = text.split('').filter((i) => i === '�').length
67+
68+
if (err / sum > 0.3) {
69+
result.encode = item.value
70+
result.value = text
71+
}
72+
} catch {
73+
continue
74+
}
75+
}
76+
}
77+
78+
if (!result.encode) {
79+
result.encode = 'utf8'
80+
}
81+
82+
if (!result.value) {
83+
result.value = iconv.decode(buffer, result.encode)
84+
}
85+
86+
return result
87+
}
88+
89+
export const isBinaryContent = async (blob: Blob) => {
4690
const slice = blob.slice(0, 1024)
4791
const arrayBuffer = await slice.arrayBuffer()
4892
const bytes = new Uint8Array(arrayBuffer)

0 commit comments

Comments
 (0)