Files
akmon/uni_modules/lime-file-utils/utssdk/index.uts
2026-01-20 08:04:15 +08:00

110 lines
2.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @ts-nocheck
// fileToBase64, fileToDataURL,dataURLToFile
export function fileToBase64(filePath : string) {
return new Promise((resolve, reject)=>{
if(uni.canIUse('getFileSystemManager')){
uni.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: (res) => {
resolve(res.data)
},
fail: (error) => {
console.error({ error, path })
reject(error)
}
})
} else {
reject('fileToBase64环境不支持')
}
})
}
export function fileToDataURL(filePath : string) {
let extension = path.substring(path.lastIndexOf('.') + 1);
const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "svg"];
const isImageFile = imageExtensions.includes(extension.toLowerCase());
let prefix = ''
if (isImageFile) {
prefix = 'image/';
if(extension == 'svg') {
extension += '+xml'
}
} else if (extension === 'pdf') {
prefix = 'application/pdf';
} else if (extension === 'txt') {
prefix = 'text/plain';
} else {
// 添加更多文件类型的判断
// 如果不是图片、PDF、文本等类型可以设定默认的前缀或采取其他处理
prefix = 'application/octet-stream';
}
return fileToBase64(filePath).then(res => `data:${prefix}${extension};base64,${res}`)
}
function getFileExtensionFromDataURL(dataURL : string) : string {
const commaIndex = dataURL.indexOf(",");
const mimeType = dataURL.substring(0, commaIndex).replace("data:", "").replace(";base64", "");
const mimeTypeParts = mimeType.split("/");
return mimeTypeParts[1];
}
function getPlatform():Uni {
// #ifdef MP-WEIXIN
return wx
// #endif
// #ifdef MP-BAIDU
return swan
// #endif
// #ifdef MP-ALIPAY
return my
// #endif
// #ifdef MP-JD
return jd
// #endif
// #ifdef MP-QQ
return qq
// #endif
// #ifdef MP-360
return qh
// #endif
// #ifdef MP-KUAISHOU
return ks
// #endif
// #ifdef MP-LARK||MP-TOUTIAO
return tt
// #endif
// #ifdef MP-DINGTALK
return dd
// #endif
// #ifdef QUICKAPP-WEBVIEW || QUICKAPP-WEBVIEW-UNION || QUICKAPP-WEBVIEW-HUAWEI
return qa
// #endif
return uni
}
export function dataURLToFile(dataURL : string, filename : NullableString = null) {
return new Promise((resolve, reject) => {
const name = filename ?? `${Date.now()}.${getFileExtensionFromDataURL(dataURL)}`;
const commaIndex = dataURL.indexOf(",");
const base64 = dataURL.substring(commaIndex + 1);
const platform = getPlatform()
const filePath = `${platform.env.USER_DATA_PATH}/${name}`;
fs.writeFile({
filePath,
data: base64,
encoding: 'base64',
success() {
resolve(filePath)
},
fail(err) {
reject(err)
}
})
})
}