Initial commit of akmon project
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"minSdkVersion": "21"
|
||||
}
|
||||
238
uni_modules/lime-file-utils/utssdk/app-android/index.uts
Normal file
238
uni_modules/lime-file-utils/utssdk/app-android/index.uts
Normal file
@@ -0,0 +1,238 @@
|
||||
import Base64 from "android.util.Base64";
|
||||
import MimeTypeMap from "android.webkit.MimeTypeMap";
|
||||
import ByteArrayOutputStream from 'java.io.ByteArrayOutputStream';
|
||||
|
||||
import File from "java.io.File";
|
||||
import FileInputStream from "java.io.FileInputStream";
|
||||
import FileOutputStream from "java.io.FileOutputStream";
|
||||
import InputStream from 'java.io.InputStream';
|
||||
|
||||
// import IOException from "java.io.IOException";
|
||||
import { ProcessFileOptions, NullableString } from '../interface'
|
||||
type NullByteArray = ByteArray | null
|
||||
|
||||
function inputStreamToArray(inputStream : InputStream) : NullByteArray {
|
||||
try {
|
||||
let bos : ByteArrayOutputStream = new ByteArrayOutputStream()
|
||||
let bytes : ByteArray = new ByteArray(1024)
|
||||
|
||||
do {
|
||||
let length = inputStream.read(bytes)
|
||||
if (length != -1) {
|
||||
bos.write(bytes, 0, length)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} while (true)
|
||||
bos.close()
|
||||
return bos.toByteArray()
|
||||
} catch (e : Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getMimeType(filePath : string) : NullableString {
|
||||
const extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
|
||||
if (extension == null) return null
|
||||
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
|
||||
}
|
||||
|
||||
export function getResourcePath(path : string) : string | null {
|
||||
let uri = path
|
||||
if (uri.startsWith("http") || uri.startsWith("<svg") || uri.startsWith("data:image/")) {
|
||||
return uri
|
||||
}
|
||||
if (uri.startsWith("file://")) {
|
||||
uri = uri.substring("file://".length)
|
||||
} else if (uri.startsWith("unifile://")) {
|
||||
uri = UTSAndroid.convert2AbsFullPath(uri)
|
||||
} else {
|
||||
uri = UTSAndroid.convert2AbsFullPath(uri)
|
||||
if (uri.startsWith("/android_asset/")) {
|
||||
try {
|
||||
const context = UTSAndroid.getUniActivity()!;
|
||||
const inputStream = context.getResources()!.getAssets().open(path.replace('/android_asset/', ''))
|
||||
inputStream.close();
|
||||
return uri
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
const file = new File(uri)
|
||||
if (file.exists()) {
|
||||
return uri
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 检查路径存在性及类型 (Android 实现)
|
||||
* @param path 要检查的完整路径(支持内部存储和外部存储路径)
|
||||
* @return Pair<是否存在, 是否是目录>
|
||||
*/
|
||||
export function checkExistence(filePath : string):boolean[] {
|
||||
const path = getResourcePath(filePath)
|
||||
if(path == null) return [false, false]
|
||||
const file = new File(path)
|
||||
const exists = file.exists()
|
||||
|
||||
if(exists) {
|
||||
return [true, file.isDirectory]
|
||||
} else {
|
||||
return [false, false]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否存在
|
||||
* @param path 要检查的完整路径
|
||||
*/
|
||||
export function isExists(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否是存在的目录
|
||||
* @param path 要检查的完整路径
|
||||
*/
|
||||
export function isDirectory(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && result[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查指定路径是否为存在的文件
|
||||
* @param path 要检查的完整路径
|
||||
* @return 当且仅当路径存在且是普通文件时返回 true
|
||||
*/
|
||||
export function isFile(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && !result[1]
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function fileToBase64(filePath : string) : NullableString {
|
||||
try {
|
||||
const context = UTSAndroid.getUniActivity()!;
|
||||
let path = filePath;
|
||||
let imageBytes : NullByteArray = null
|
||||
|
||||
if (path.startsWith("file://")) {
|
||||
path = path.replace("file://", "")
|
||||
} else {
|
||||
// if(!path.startsWith("/storage") && !path.startsWith("/android_asset/"))
|
||||
// path = UTSAndroid.getResourcePath(path)
|
||||
path = UTSAndroid.convert2AbsFullPath(path)
|
||||
}
|
||||
|
||||
if (path.startsWith("/android_asset/")) {
|
||||
imageBytes = inputStreamToArray(context.getResources()!.getAssets().open(path.replace('/android_asset/', '')))
|
||||
} else {
|
||||
const file = new File(path)
|
||||
if (file.exists()) {
|
||||
let fis : FileInputStream = new FileInputStream(file);
|
||||
imageBytes = inputStreamToArray(fis);
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
if (imageBytes == null) return null
|
||||
return Base64.encodeToString(imageBytes, Base64.NO_WRAP) //Base64.DEFAULT 解决换行问题
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
export function fileToDataURL(filePath : string) : NullableString {
|
||||
const base64 = fileToBase64(filePath)
|
||||
const mimeType = getMimeType(filePath);
|
||||
if (base64 == null || mimeType == null) return null;
|
||||
return "data:" + mimeType + ";base64," + base64;
|
||||
}
|
||||
|
||||
|
||||
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 dataURLToBytes(dataURL : string) : ByteArray {
|
||||
const commaIndex = dataURL.indexOf(",");
|
||||
const base64 = dataURL.substring(commaIndex + 1);
|
||||
return Base64.decode(base64, Base64.DEFAULT);
|
||||
}
|
||||
|
||||
export function dataURLToFile(dataURL : string, filename : NullableString = null) : NullableString {
|
||||
try {
|
||||
const bytes = dataURLToBytes(dataURL);
|
||||
const name = filename ?? `${Date.now()}.${getFileExtensionFromDataURL(dataURL)}`;
|
||||
const cacheDir = UTSAndroid.getAppCachePath()!;
|
||||
const destFile = new File(cacheDir, name);
|
||||
const path = new File(cacheDir);
|
||||
if(!path.exists()){
|
||||
path.mkdir();
|
||||
}
|
||||
const fos = new FileOutputStream(destFile)
|
||||
fos.write(bytes);
|
||||
fos.close();
|
||||
return `${cacheDir}${name}`
|
||||
} catch (e) {
|
||||
console.error('dataURLToFile::', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// function requestSystemPermission(fun:()=> void) {
|
||||
// let permissionNeed = ["android.permission.WRITE_EXTERNAL_STORAGE"]
|
||||
// UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, permissionNeed, function (allRight : boolean, _ : string[]) {
|
||||
// if (allRight) {
|
||||
// // 权限请求成功
|
||||
// console.log(`allRight`, allRight)
|
||||
// fun()
|
||||
// } else {
|
||||
// //用户拒绝了部分权限
|
||||
// }
|
||||
// }, function (_ : boolean, _ : string[]) {
|
||||
// //用户拒绝了部分权限
|
||||
// })
|
||||
// }
|
||||
|
||||
|
||||
export function processFile(options : ProcessFileOptions) {
|
||||
|
||||
if (options.type == 'toBase64') {
|
||||
const res = fileToBase64(options.path)
|
||||
const err = 'fileToBase64: 解析失败'
|
||||
if (res != null) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if (options.type == 'toDataURL') {
|
||||
const res = fileToDataURL(options.path)
|
||||
const err = 'fileToDataURL: 解析失败'
|
||||
if (res != null) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if (options.type == 'toFile') {
|
||||
const res = dataURLToFile(options.path, options.filename)
|
||||
const err = 'dataURLToFile: 解析失败'
|
||||
if (res != null) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
199
uni_modules/lime-file-utils/utssdk/app-harmony/index.uts
Normal file
199
uni_modules/lime-file-utils/utssdk/app-harmony/index.uts
Normal file
@@ -0,0 +1,199 @@
|
||||
// @ts-nocheck
|
||||
export * from '../interface'
|
||||
import type { ProcessFileOptions, NullableString } from '../interface'
|
||||
import { fileIo } from '@kit.CoreFileKit';
|
||||
// import { getRealPath } from '@dcloudio/uni-runtime'
|
||||
import buffer from '@ohos.buffer';
|
||||
import util from '@ohos.util';
|
||||
import { getEnv } from '@dcloudio/uni-runtime';
|
||||
// 常见MIME类型映射(可根据需求扩展)
|
||||
const mimeTypeMap : Record<string, string> = {
|
||||
// 图片类型
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'png': 'image/png',
|
||||
'gif': 'image/gif',
|
||||
'webp': 'image/webp',
|
||||
'svg': 'image/svg+xml',
|
||||
|
||||
// 文本类型
|
||||
'txt': 'text/plain',
|
||||
'html': 'text/html',
|
||||
'htm': 'text/html',
|
||||
'css': 'text/css',
|
||||
'csv': 'text/csv',
|
||||
|
||||
// 应用类型
|
||||
'js': 'application/javascript',
|
||||
'json': 'application/json',
|
||||
'pdf': 'application/pdf',
|
||||
'zip': 'application/zip',
|
||||
'xml': 'application/xml',
|
||||
|
||||
// 音频类型
|
||||
'mp3': 'audio/mpeg',
|
||||
'wav': 'audio/wav',
|
||||
|
||||
// 视频类型
|
||||
'mp4': 'video/mp4',
|
||||
'mov': 'video/quicktime'
|
||||
};
|
||||
/**
|
||||
* 检查路径存在性及类型 (Android 实现)
|
||||
* @param path 要检查的完整路径(支持内部存储和外部存储路径)
|
||||
* @return Pair<是否存在, 是否是目录>
|
||||
*/
|
||||
export function checkExistence(filePath : string) : boolean[] {
|
||||
// const path = getRealPath(filePath)
|
||||
const path = UTSHarmony.getResourcePath(filePath)
|
||||
const exists = fileIo.accessSync(path)
|
||||
const isDirectory = exists ? fileIo.statSync(path).isDirectory() : false;
|
||||
return [exists, isDirectory]
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否存在
|
||||
* @param path 要检查的完整路径
|
||||
*/
|
||||
export function isExists(filePath : string) : boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否是存在的目录
|
||||
* @param path 要检查的完整路径
|
||||
*/
|
||||
export function isDirectory(filePath : string) : boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && result[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查指定路径是否为存在的文件
|
||||
* @param path 要检查的完整路径
|
||||
* @return 当且仅当路径存在且是普通文件时返回 true
|
||||
*/
|
||||
export function isFile(filePath : string) : boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && !result[1]
|
||||
}
|
||||
|
||||
// 获取文件扩展名(自动处理大小写和特殊路径)
|
||||
function getFileExtension(filePath : string) : string | null {
|
||||
// 处理包含查询参数或哈希的路径(如网络路径)
|
||||
const cleanPath = filePath.split(/[?#]/)[0];
|
||||
const fileName = cleanPath.split('/').pop() || '';
|
||||
const dotIndex = fileName.lastIndexOf('.');
|
||||
|
||||
if (dotIndex <= 0) return null; // 排除类似 ".hiddenfile" 的情况
|
||||
return fileName.slice(dotIndex + 1).toLowerCase();
|
||||
}
|
||||
|
||||
|
||||
// 根据扩展名获取MIME类型
|
||||
function getMimeType(extension : string | null) : string {
|
||||
if (!extension) return 'application/octet-stream';
|
||||
return mimeTypeMap[extension] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
export function fileToBase64(filePath : string) : string | null {
|
||||
if (!isExists(filePath)) return null
|
||||
const path = UTSHarmony.getResourcePath(filePath)
|
||||
const file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY);
|
||||
// 获取文件状态
|
||||
const stat = fileIo.statSync(path);
|
||||
// 创建缓冲区
|
||||
const buf = new ArrayBuffer(stat.size);
|
||||
// 读取文件内容
|
||||
// fileIo.read(fd, buf);
|
||||
fileIo.readSync(file.fd, buf);
|
||||
fileIo.closeSync(file);
|
||||
// 转换为Base64
|
||||
let base64Helper = new util.Base64Helper();
|
||||
let array = new Uint8Array(buf);
|
||||
let result = base64Helper.encodeToStringSync(array, util.Type.MIME)
|
||||
return result
|
||||
|
||||
}
|
||||
|
||||
export function fileToDataURL(filePath : string) : string | null {
|
||||
try {
|
||||
const base64 = fileToBase64(filePath)
|
||||
if (!base64) return null
|
||||
const extension = getFileExtension(filePath);
|
||||
const mimeType = getMimeType(extension);
|
||||
return `data:${mimeType};base64,${base64}`;
|
||||
} catch (err) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function dataURLToFile(dataURL : string, filename : NullableString = null) : string | null {
|
||||
// 格式校验正则表达式
|
||||
const dataURLRegex = /^data:([a-zA-Z]+\/[a-zA-Z0-9-+.]+(;[a-zA-Z0-9-]+=[a-zA-Z0-9-]+)*)?(;base64)?,(.*)$/;
|
||||
const match = dataURL.match(dataURLRegex);
|
||||
|
||||
const commaIndex = dataURL.indexOf(",");
|
||||
const mimeType = dataURL.substring(0, commaIndex).replace("data:", "").replace(";base64", "");
|
||||
const mimeTypeParts = mimeType.split("/");
|
||||
|
||||
if (!match) return null
|
||||
|
||||
const mediaType = match[1] || 'text/plain';
|
||||
const extension = Object.entries(mimeTypeMap).find(it => it[1] == mediaType)?.[0] ?? mimeTypeParts[1]
|
||||
if(!extension) return null
|
||||
const base64 = dataURL.substring(commaIndex + 1);
|
||||
const tempFileName = filename ?? `${Date.now()}.${extension}`
|
||||
|
||||
const tempDirPath = `${getEnv().TEMP_PATH}/file`
|
||||
const tempFilePath : string = `${tempDirPath}/${tempFileName}`
|
||||
if (!fileIo.accessSync(tempDirPath)) {
|
||||
fileIo.mkdirSync(tempDirPath, true)
|
||||
}
|
||||
try {
|
||||
const uint8Array = buffer.from(base64, 'base64').buffer
|
||||
const file = fileIo.openSync(tempFilePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
|
||||
fileIo.writeSync(file.fd, uint8Array);
|
||||
|
||||
return tempFilePath
|
||||
|
||||
} catch(err) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function processFile(options : ProcessFileOptions) {
|
||||
if (options.type == 'toBase64') {
|
||||
const res = fileToBase64(options.path)
|
||||
const err = 'fileToBase64: 解析失败'
|
||||
if (res) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if (options.type == 'toDataURL') {
|
||||
const res = fileToDataURL(options.path)
|
||||
const err = 'fileToDataURL: 解析失败'
|
||||
if (res) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if (options.type == 'toFile') {
|
||||
const res = dataURLToFile(options.path, options.filename)
|
||||
const err = 'dataURLToFile: 解析失败'
|
||||
if (res) {
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
3
uni_modules/lime-file-utils/utssdk/app-ios/config.json
Normal file
3
uni_modules/lime-file-utils/utssdk/app-ios/config.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"deploymentTarget": "9"
|
||||
}
|
||||
141
uni_modules/lime-file-utils/utssdk/app-ios/index.uts
Normal file
141
uni_modules/lime-file-utils/utssdk/app-ios/index.uts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { UTSiOS } from "DCloudUTSFoundation"
|
||||
import { URL, FileManager, NSData, Data } from 'Foundation';
|
||||
import { UTTypeCreatePreferredIdentifierForTag, kUTTagClassFilenameExtension, UTTypeCopyPreferredTagWithClass, kUTTagClassMIMEType } from "MobileCoreServices"
|
||||
import { ProcessFileOptions, NullableString } from '../interface'
|
||||
import { Bool } from 'Swift';
|
||||
|
||||
|
||||
export function getResourcePath(filePath : string) : string {
|
||||
let path = filePath;
|
||||
if (path.startsWith("http") || path.startsWith("<svg") || path.startsWith("data:image/")) {
|
||||
return path
|
||||
}
|
||||
if (path.startsWith("file://")) {
|
||||
path = path.substring(7) //path.replace("file://", "")
|
||||
} else if (path.startsWith("unifile://")) {
|
||||
path = UTSiOS.convert2AbsFullPath(filePath);
|
||||
} else if (!path.startsWith("/var/")) {
|
||||
path = UTSiOS.getResourcePath(filePath);
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
export function checkExistence(filePath : string):boolean[] {
|
||||
let path = getResourcePath(filePath)
|
||||
let isDirectory:ObjCBool = false
|
||||
const exists = FileManager.default.fileExists(atPath = path, isDirectory = UTSiOS.getPointer(isDirectory))
|
||||
return [exists,isDirectory.boolValue]
|
||||
}
|
||||
|
||||
export function isFile(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && !result[1]
|
||||
}
|
||||
|
||||
export function isExists(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0]
|
||||
}
|
||||
|
||||
export function isDirectory(filePath : string):boolean {
|
||||
const result = checkExistence(filePath);
|
||||
return result[0] && result[1]
|
||||
}
|
||||
|
||||
|
||||
function getMimeType(filePath : string) : NullableString {
|
||||
let path = getResourcePath(filePath)
|
||||
if(!FileManager.default.fileExists(atPath = path)) return null
|
||||
const pathExtension = new URL(fileURLWithPath = path).pathExtension;
|
||||
const mimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, null)?.takeRetainedValue()
|
||||
if(mimeType == null) return null
|
||||
const mimeTypeString = UTTypeCopyPreferredTagWithClass(mimeType!, kUTTagClassMIMEType)?.takeRetainedValue();
|
||||
if(mimeTypeString == null) return null
|
||||
return mimeTypeString as string
|
||||
}
|
||||
|
||||
export function fileToBase64(filePath : string) : NullableString {
|
||||
let path = getResourcePath(filePath)
|
||||
if(!FileManager.default.fileExists(atPath = path)) return null;
|
||||
const fileData = FileManager.default.contents(atPath = path);
|
||||
if(fileData == null) return null;
|
||||
return fileData!.base64EncodedString(options = NSData.Base64EncodingOptions.lineLength64Characters)//.replace(/\s+/g,'')
|
||||
}
|
||||
|
||||
export function fileToDataURL(filePath : string) : NullableString {
|
||||
const base64 = fileToBase64(filePath)
|
||||
const mimeType = getMimeType(filePath)
|
||||
if(base64 == null || mimeType == null) return null
|
||||
return ("data:" + mimeType! + ";base64," + base64!)//.replace(/\s+/g,'');
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
|
||||
export function dataURLToFile(dataURL : string, filename : NullableString = null) : NullableString {
|
||||
|
||||
const commaIndex = dataURL.indexOf(",");
|
||||
const base64 = dataURL.substring(commaIndex + 1);
|
||||
const data = new Data(base64Encoded = base64);
|
||||
// #ifdef UNI-APP-X
|
||||
const dataPath = UTSiOS.getDataPath();
|
||||
// #endif
|
||||
// #ifndef UNI-APP-X
|
||||
const dataPath = UTSiOS.getDataPath().replace(/data$/, "doc");
|
||||
// #endif
|
||||
const name = filename ?? `${Date.now()}.${getFileExtensionFromDataURL(dataURL)}`;
|
||||
if(data == null) return null
|
||||
|
||||
let temporaryDirectoryURL = new URL(fileURLWithPath = dataPath);
|
||||
let fileURL = temporaryDirectoryURL.appendingPathComponent(name);
|
||||
try{
|
||||
UTSiOS.try(data!.write(to = fileURL))
|
||||
return `${dataPath}/${name}`
|
||||
}catch(e){
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function processFile(options: ProcessFileOptions){
|
||||
if(options.type == 'toBase64'){
|
||||
const res = fileToBase64(options.path)
|
||||
const err = 'fileToBase64: 解析失败'
|
||||
if(res != null){
|
||||
options.success?.(res!)
|
||||
options.complete?.(res!)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if(options.type == 'toDataURL'){
|
||||
const res = fileToDataURL(options.path)
|
||||
const err = 'fileToDataURL: 解析失败'
|
||||
if(res != null){
|
||||
options.success?.(res!)
|
||||
options.complete?.(res!)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
} else if(options.type == 'toFile'){
|
||||
const res = dataURLToFile(options.path, options.filename)
|
||||
const err = 'dataURLToFile: 解析失败'
|
||||
if(res != null){
|
||||
options.success?.(res!)
|
||||
options.complete?.(res!)
|
||||
} else {
|
||||
options.complete?.(err)
|
||||
options.fail?.(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
110
uni_modules/lime-file-utils/utssdk/index.uts
Normal file
110
uni_modules/lime-file-utils/utssdk/index.uts
Normal file
@@ -0,0 +1,110 @@
|
||||
// @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)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
}
|
||||
38
uni_modules/lime-file-utils/utssdk/interface.uts
Normal file
38
uni_modules/lime-file-utils/utssdk/interface.uts
Normal file
@@ -0,0 +1,38 @@
|
||||
// @ts-nocheck
|
||||
export type NullableString = string | null
|
||||
export type ConversionType = 'toBase64' | 'toDataURL' | 'toFile'
|
||||
|
||||
// #ifndef APP-HARMONY
|
||||
export type ProcessFileOptions = {
|
||||
type : ConversionType
|
||||
path: string
|
||||
filename?: string
|
||||
success ?: (res : string) => void
|
||||
fail ?: (res : any) => void
|
||||
complete ?: (res : any) => void
|
||||
}
|
||||
// #endif
|
||||
// #ifdef APP-HARMONY
|
||||
export interface ProcessFileOptions {
|
||||
type : ConversionType
|
||||
path: string
|
||||
filename?: string
|
||||
success ?: (res : string) => void
|
||||
fail ?: (res : any) => void
|
||||
complete ?: (res : any) => void
|
||||
}
|
||||
// #endif
|
||||
|
||||
/**
|
||||
* 错误码
|
||||
* 根据uni错误码规范要求,建议错误码以90开头,以下是错误码示例:
|
||||
* - 9010001 错误信息1
|
||||
* - 9010002 错误信息2
|
||||
*/
|
||||
export type ProcessFileErrorCode = 9010001 | 9010002;
|
||||
/**
|
||||
* myApi 的错误回调参数
|
||||
*/
|
||||
export interface ProcessFileFail extends IUniError {
|
||||
errCode : ProcessFileErrorCode
|
||||
};
|
||||
40
uni_modules/lime-file-utils/utssdk/unierror.uts
Normal file
40
uni_modules/lime-file-utils/utssdk/unierror.uts
Normal file
@@ -0,0 +1,40 @@
|
||||
// @ts-nocheck
|
||||
/* 此规范为 uni 规范,可以按照自己的需要选择是否实现 */
|
||||
import { MyApiErrorCode, MyApiFail } from "./interface.uts"
|
||||
/**
|
||||
* 错误主题
|
||||
* 注意:错误主题一般为插件名称,每个组件不同,需要使用时请更改。
|
||||
* [可选实现]
|
||||
*/
|
||||
export const UniErrorSubject = 'uts-api';
|
||||
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
* @UniError
|
||||
* [可选实现]
|
||||
*/
|
||||
export const MyAPIErrors : Map<MyApiErrorCode, string> = new Map([
|
||||
/**
|
||||
* 错误码及对应的错误信息
|
||||
*/
|
||||
[9010001, 'custom error mseeage1'],
|
||||
[9010002, 'custom error mseeage2'],
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* 错误对象实现
|
||||
*/
|
||||
export class MyApiFailImpl extends UniError implements MyApiFail {
|
||||
|
||||
/**
|
||||
* 错误对象构造函数
|
||||
*/
|
||||
constructor(errCode : MyApiErrorCode) {
|
||||
super();
|
||||
this.errSubject = UniErrorSubject;
|
||||
this.errCode = errCode;
|
||||
this.errMsg = MyAPIErrors.get(errCode) ?? "";
|
||||
}
|
||||
}
|
||||
95
uni_modules/lime-file-utils/utssdk/web/index.uts
Normal file
95
uni_modules/lime-file-utils/utssdk/web/index.uts
Normal file
@@ -0,0 +1,95 @@
|
||||
// @ts-nocheck
|
||||
export * from '../interface'
|
||||
import { ProcessFileOptions, NullableString } from '../interface'
|
||||
|
||||
|
||||
|
||||
function readFileAs(
|
||||
file : File | string,
|
||||
method : 'readAsDataURL' | 'readAsText' | 'readAsArrayBuffer' | 'readAsBinaryString'
|
||||
) : Promise<string | ArrayBuffer> {
|
||||
|
||||
try {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
let blob : Blob | null = null;
|
||||
if (typeof file === 'string') {
|
||||
const response = await fetch(file);
|
||||
if (!response || !response.ok) {
|
||||
return reject('readFileAs null');
|
||||
}
|
||||
blob = await response!.blob();
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader[method](blob ?? file);
|
||||
reader.onload = () => {
|
||||
resolve(reader.result);
|
||||
};
|
||||
reader.onerror = (error) => {
|
||||
reject(error);
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export function fileToBase64(filePath : string | File) : Promise<string> {
|
||||
return readFileAs(filePath, 'readAsDataURL').then(result => (result as string).split(',')?.[1])
|
||||
}
|
||||
|
||||
export function fileToDataURL(filePath : string | File) : Promise<string> {
|
||||
return readFileAs(filePath, 'readAsDataURL').then(result => (result as string));
|
||||
}
|
||||
|
||||
export function dataURLToFile(dataURL : string, filename : NullableString = null) : Promise<string> {
|
||||
return new Promise((resolve, reject)=>{
|
||||
// mime类型
|
||||
let mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
|
||||
//base64 解码
|
||||
let byteString = atob(dataURL.split(',')[1]);
|
||||
if (byteString == null) {
|
||||
return reject('dataURLToFile: 解析失败')
|
||||
};
|
||||
//创建缓冲数组
|
||||
let arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
//创建视图
|
||||
let intArray = new Uint8Array(arrayBuffer);
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
intArray[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
// @ts-ignore
|
||||
const blob = new Blob([intArray], { type: mimeString });
|
||||
resolve(URL.createObjectURL(blob))
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
|
||||
export function processFile(options: ProcessFileOptions){
|
||||
if(options.type == 'toBase64'){
|
||||
fileToBase64(options.path).then(res =>{
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
}).catch(err =>{
|
||||
options.fail?.(err)
|
||||
options.complete?.(err)
|
||||
})
|
||||
} else if(options.type == 'toDataURL'){
|
||||
fileToDataURL(options.path).then(res =>{
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
}).catch(err =>{
|
||||
options.fail?.(err)
|
||||
options.complete?.(err)
|
||||
})
|
||||
} else if(options.type == 'toFile'){
|
||||
dataURLToFile(options.path).then(res =>{
|
||||
options.success?.(res)
|
||||
options.complete?.(res)
|
||||
}).catch(err =>{
|
||||
options.fail?.(err)
|
||||
options.complete?.(err)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user