Initial commit of akmon project
This commit is contained in:
24
uni_modules/lime-file-utils/changelog.md
Normal file
24
uni_modules/lime-file-utils/changelog.md
Normal file
@@ -0,0 +1,24 @@
|
||||
## 0.1.2(2025-09-15)
|
||||
- fix: 修复鸿蒙next 对音频无法转换的问题
|
||||
## 0.1.1(2025-08-30)
|
||||
- fix: 修复鸿蒙next不触发成功和失败回调
|
||||
## 0.1.0(2025-08-24)
|
||||
- feat: 兼容鸿蒙Next
|
||||
## 0.0.9(2025-05-21)
|
||||
- fix: 修复鸿蒙next报错问题,但未兼容
|
||||
## 0.0.8(2025-03-21)
|
||||
- fix: 修复checkExistence path问题
|
||||
## 0.0.7(2025-02-19)
|
||||
- feat: 更新uniapp ios路径问题
|
||||
## 0.0.6(2024-12-16)
|
||||
- chore: 更新文档
|
||||
## 0.0.5(2024-11-21)
|
||||
- fix: 修复vue2类型报错问题
|
||||
## 0.0.4(2024-10-26)
|
||||
- fix: 修复空目录的情况
|
||||
## 0.0.3(2024-08-29)
|
||||
- fix: 修复ios uri问题
|
||||
## 0.0.2(2024-06-25)
|
||||
- fix: 修复安卓无法读取`storage`目录的问题
|
||||
## 0.0.1(2024-05-12)
|
||||
- init
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
106
uni_modules/lime-file-utils/package.json
Normal file
106
uni_modules/lime-file-utils/package.json
Normal file
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"id": "lime-file-utils",
|
||||
"displayName": "lime-file-utils 文件转换",
|
||||
"version": "0.1.2",
|
||||
"description": "fileUtils是一款在文件或图像和 Base64 之间进行转换的UTS API,图片转base64,base64转文件,兼容(h5,ios,安卓,鸿蒙Next)",
|
||||
"keywords": [
|
||||
"lime-file-utils",
|
||||
"base64",
|
||||
"图像转换工具",
|
||||
"文件转换工具"
|
||||
],
|
||||
"repository": "",
|
||||
"engines": {
|
||||
"HBuilderX": "^4.15",
|
||||
"uni-app": "^4.66",
|
||||
"uni-app-x": "^4.76"
|
||||
},
|
||||
"dcloudext": {
|
||||
"type": "uts",
|
||||
"sale": {
|
||||
"regular": {
|
||||
"price": "0.00"
|
||||
},
|
||||
"sourcecode": {
|
||||
"price": "0.00"
|
||||
}
|
||||
},
|
||||
"contact": {
|
||||
"qq": ""
|
||||
},
|
||||
"declaration": {
|
||||
"ads": "无",
|
||||
"data": "无",
|
||||
"permissions": "无"
|
||||
},
|
||||
"npmurl": "",
|
||||
"darkmode": "x",
|
||||
"i18n": "x",
|
||||
"widescreen": "x"
|
||||
},
|
||||
"uni_modules": {
|
||||
"dependencies": [],
|
||||
"encrypt": [],
|
||||
"platforms": {
|
||||
"cloud": {
|
||||
"tcb": "√",
|
||||
"aliyun": "√",
|
||||
"alipay": "√"
|
||||
},
|
||||
"client": {
|
||||
"uni-app": {
|
||||
"vue": {
|
||||
"vue2": "√",
|
||||
"vue3": "√"
|
||||
},
|
||||
"web": {
|
||||
"safari": "√",
|
||||
"chrome": "√"
|
||||
},
|
||||
"app": {
|
||||
"vue": "√",
|
||||
"nvue": "-",
|
||||
"android": {
|
||||
"extVersion": "",
|
||||
"minVersion": "21"
|
||||
},
|
||||
"ios": "√",
|
||||
"harmony": "√"
|
||||
},
|
||||
"mp": {
|
||||
"weixin": "-",
|
||||
"alipay": "-",
|
||||
"toutiao": "-",
|
||||
"baidu": "-",
|
||||
"kuaishou": "-",
|
||||
"jd": "-",
|
||||
"harmony": "-",
|
||||
"qq": "-",
|
||||
"lark": "-"
|
||||
},
|
||||
"quickapp": {
|
||||
"huawei": "-",
|
||||
"union": "-"
|
||||
}
|
||||
},
|
||||
"uni-app-x": {
|
||||
"web": {
|
||||
"safari": "√",
|
||||
"chrome": "√"
|
||||
},
|
||||
"app": {
|
||||
"android": {
|
||||
"extVersion": "",
|
||||
"minVersion": "21"
|
||||
},
|
||||
"ios": "√",
|
||||
"harmony": "√"
|
||||
},
|
||||
"mp": {
|
||||
"weixin": "-"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
96
uni_modules/lime-file-utils/readme - 副本.md
Normal file
96
uni_modules/lime-file-utils/readme - 副本.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# lime-file-utils
|
||||
- fileUtils 是一款可以轻松地在文件和 Base64 编码的数据之间进行转换,从而提高开发效率的UTS API工具包
|
||||
|
||||
## 文档
|
||||
🚀 [file-utils【站点1】](https://limex.qcoon.cn/native/file-utils.html)
|
||||
🌍 [file-utils【站点2】](https://limeui.netlify.app/native/file-utils.html)
|
||||
🔥 [file-utils【站点3】](https://limeui.familyzone.top/native/file-utils.html)
|
||||
|
||||
|
||||
## 安装
|
||||
插件市场导入即可
|
||||
|
||||
|
||||
## 使用
|
||||
- APP是同步函数,非APP是Promise
|
||||
|
||||
```js
|
||||
import { fileToDataURL, dataURLToFile, processFile, ProcessFileOptions } from '@/uni_modules/lime-file-utils'
|
||||
const url = ref('')
|
||||
const src = ref('')
|
||||
const base64 = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAIAAAAP3aGbAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAH40lEQVR4nO3dwXFjSRIFweba6K9yrwisQ05OBuAuAPABgmF1eVY/f//+/QNQ8L//+gEAXgkWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQIVhAxj9TL/Tz8zP1UkUv1zu+fEXF13m0+dgvrn3VH2zwV+SEBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQMbYlvDF4KRozeAKbOrjb47XDn78KctTyhfXvqIXyzNJJywgQ7CADMECMgQLyBAsIEOwgAzBAjIEC8gQLCBDsIAMwQIyVreELzanSQenW5sDt+WPv3mf4IvoXYFf/g/ihAVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWQIFpAhWEDGuS3hB7t2EV50TPfi2lfNFCcsIEOwgAzBAjIEC8gQLCBDsIAMwQI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AvIECwgQ7CADMECMgQLyBAsIEOwgAzBAjL+DwEJMVCBletEAAAAAElFTkSuQmCC`
|
||||
|
||||
// #ifdef WEB || MP
|
||||
fileToDataURL('/static/logo.png').then(res => {
|
||||
url.value = res
|
||||
})
|
||||
dataURLToFile(base64).then(res => {
|
||||
src.value = res
|
||||
})
|
||||
// #endif
|
||||
// #ifdef APP
|
||||
url.value = fileToDataURL('/static/logo.png') ?? ''
|
||||
src.value = dataURLToFile(base64) ?? '';
|
||||
// #endif
|
||||
|
||||
// 相当于 fileToDataURL
|
||||
processFile({
|
||||
type: 'toDataURL',
|
||||
path: '/static/logo.png',
|
||||
success: (res: string)=>{
|
||||
url.value = res
|
||||
}
|
||||
} as ProcessFileOptions)
|
||||
|
||||
// 相当于 dataURLToFile
|
||||
processFile({
|
||||
type: 'toFile',
|
||||
path: base64,
|
||||
success: (res: string)=>{
|
||||
src.value = res
|
||||
}
|
||||
} as ProcessFileOptions)
|
||||
```
|
||||
|
||||
|
||||
## fileToDataURL
|
||||
将`文件`或`图片`转成 `URL(data URL)`,接收一个文件路径,APP 返回的是`DataURL`或`null`, 非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
fileToDataURL(filePath : string)
|
||||
```
|
||||
|
||||
## fileToBase64
|
||||
将`文件`或`图片`转成 `Base64`, 接收一个文件路径,APP 返回的是`Base64`或`null`, 非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
fileToBase64(filePath : string)
|
||||
```
|
||||
|
||||
## dataURLToFile
|
||||
将 `Base64` 编码的数据 `URL(data URL)`保存为临时路径,接收一个dataURL,参数`filename`为可选, APP返回的是`string`或`null`,非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
dataURLToFile(dataURL : string, filename : NullableString = null)
|
||||
```
|
||||
|
||||
## processFile
|
||||
是上面三个函数的总和,接收`ProcessFileOptions`
|
||||
|
||||
```js
|
||||
processFile({
|
||||
type: 'toBase64' | 'toDataURL' | 'toFile',
|
||||
path: string,
|
||||
filename?: string,//如果是toFile,则可以设置保存文件的文件名
|
||||
success ?: (res : string) {},
|
||||
fail ?: (res : any) {},
|
||||
complete ?: (res : any) {}
|
||||
} as ProcessFileOptions)
|
||||
```
|
||||
|
||||
|
||||
## 打赏
|
||||
|
||||
如果你觉得本插件,解决了你的问题,赠人玫瑰,手留余香。
|
||||

|
||||

|
||||
142
uni_modules/lime-file-utils/readme.md
Normal file
142
uni_modules/lime-file-utils/readme.md
Normal file
@@ -0,0 +1,142 @@
|
||||
# lime-file-utils 文件工具组件
|
||||
fileUtils 是一款可以轻松地在文件和 Base64 编码的数据之间进行转换的UTS API工具包,提供了文件与Base64、DataURL之间的相互转换功能,大大提高开发效率。适用于需要处理图片预览、文件上传、数据传输等场景。
|
||||
|
||||
> 插件依赖:无特殊依赖
|
||||
|
||||
## 文档链接
|
||||
📚 组件详细文档请访问以下站点:
|
||||
- [文件工具组件文档 - 站点1](https://limex.qcoon.cn/native/file-utils.html)
|
||||
- [文件工具组件文档 - 站点2](https://limeui.netlify.app/native/file-utils.html)
|
||||
- [文件工具组件文档 - 站点3](https://limeui.familyzone.top/native/file-utils.html)
|
||||
|
||||
## 安装方法
|
||||
1. 在uni-app插件市场中搜索并导入`lime-file-utils`
|
||||
2. 导入后可能需要重新编译项目
|
||||
3. 在页面中通过import引入相关API
|
||||
|
||||
## 代码演示
|
||||
|
||||
### 基础用法
|
||||
- APP是同步函数,非APP是Promise
|
||||
|
||||
```js
|
||||
import { fileToDataURL, dataURLToFile, processFile, ProcessFileOptions } from '@/uni_modules/lime-file-utils'
|
||||
const url = ref('')
|
||||
const src = ref('')
|
||||
const base64 = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAIAAAAP3aGbAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAH40lEQVR4nO3dwXFjSRIFweba6K9yrwisQ05OBuAuAPABgmF1eVY/f//+/QNQ8L//+gEAXgkWkCFYQIZgARmCBWQIFpAhWECGYAEZggVkCBaQ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+/15X9ZJywgQ7CADMECMgQLyBAsIEOwgAzBAjIEC8gQLCBDsIAMwQIybAn3bA7corfObT72tb3hn92d4Obdhe4lBL6RYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQIZgARmCBWSc2xIevAptytRHm1pvHRzKXZtSbg7uHl273XL5V+SEBWQIFpAhWECGYAEZggVkCBaQIVhAhmABGYIFZAgWkCFYQMbP5sDtg12bQG7eObj8p//yMd3mIx28udIJC8gQLCBDsIAMwQIyBAvIECwgQ7CADMECMgQLyBAsIEOwgIyxLSHAv80JC8gQLCBDsIAMwQIyBAvIECwgQ7CADMECMgQLyBAsIEOwgAzBAjIEC8gQLCBDsIAMwQIyBAvIECwgQ7CADMECMgQLyBAsIEOwgAzBAjL+DwEJMVCBletEAAAAAElFTkSuQmCC`
|
||||
|
||||
// #ifdef WEB || MP
|
||||
fileToDataURL('/static/logo.png').then(res => {
|
||||
url.value = res
|
||||
})
|
||||
dataURLToFile(base64).then(res => {
|
||||
src.value = res
|
||||
})
|
||||
// #endif
|
||||
// #ifdef APP
|
||||
url.value = fileToDataURL('/static/logo.png') ?? ''
|
||||
src.value = dataURLToFile(base64) ?? '';
|
||||
// #endif
|
||||
|
||||
// 相当于 fileToDataURL
|
||||
processFile({
|
||||
type: 'toDataURL',
|
||||
path: '/static/logo.png',
|
||||
success: (res: string)=>{
|
||||
url.value = res
|
||||
}
|
||||
} as ProcessFileOptions)
|
||||
|
||||
// 相当于 dataURLToFile
|
||||
processFile({
|
||||
type: 'toFile',
|
||||
path: base64,
|
||||
success: (res: string)=>{
|
||||
src.value = res
|
||||
}
|
||||
} as ProcessFileOptions)
|
||||
```
|
||||
|
||||
|
||||
## fileToDataURL
|
||||
将`文件`或`图片`转成 `URL(data URL)`,接收一个文件路径,APP 返回的是`DataURL`或`null`, 非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
fileToDataURL(filePath : string)
|
||||
```
|
||||
|
||||
## fileToBase64
|
||||
将`文件`或`图片`转成 `Base64`, 接收一个文件路径,APP 返回的是`Base64`或`null`, 非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
fileToBase64(filePath : string)
|
||||
```
|
||||
|
||||
## dataURLToFile
|
||||
将 `Base64` 编码的数据 `URL(data URL)`保存为临时路径,接收一个dataURL,参数`filename`为可选, APP返回的是`string`或`null`,非APP 返回的是`Promise<string>`
|
||||
|
||||
```js
|
||||
dataURLToFile(dataURL : string, filename : NullableString = null)
|
||||
```
|
||||
|
||||
## processFile
|
||||
是上面三个函数的总和,接收`ProcessFileOptions`
|
||||
|
||||
```js
|
||||
processFile({
|
||||
type: 'toBase64' | 'toDataURL' | 'toFile',
|
||||
path: string,
|
||||
filename?: string,//如果是toFile,则可以设置保存文件的文件名
|
||||
success ?: (res : string) {},
|
||||
fail ?: (res : any) {},
|
||||
complete ?: (res : any) {}
|
||||
} as ProcessFileOptions)
|
||||
```
|
||||
|
||||
|
||||
## API文档
|
||||
|
||||
### 主要函数
|
||||
|
||||
| 函数名 | 说明 | 参数 | 返回值 |
|
||||
| --- | --- | --- | --- |
|
||||
| fileToDataURL | 将文件或图片转成DataURL | _filePath: string_ | APP: _string \| null_<br>非APP: _Promise\<string\>_ |
|
||||
| fileToBase64 | 将文件或图片转成Base64 | _filePath: string_ | APP: _string \| null_<br>非APP: _Promise\<string\>_ |
|
||||
| dataURLToFile | 将DataURL保存为临时文件 | _dataURL: string, filename?: string_ | APP: _string \| null_<br>非APP: _Promise\<string\>_ |
|
||||
| processFile | 综合处理函数 | _options: ProcessFileOptions_ | _void_ |
|
||||
|
||||
### ProcessFileOptions 参数说明
|
||||
|
||||
| 属性名 | 说明 | 类型 | 默认值 |
|
||||
| --- | --- | --- | --- |
|
||||
| type | 处理类型 | _'toDataURL' \| 'toBase64' \| 'toFile'_ | - |
|
||||
| path | 文件路径或DataURL | _string_ | - |
|
||||
| filename | 保存文件名(仅toFile类型可用) | _string_ | - |
|
||||
| success | 成功回调函数 | _(res: string) => void_ | - |
|
||||
| fail | 失败回调函数 | _(res: any) => void_ | - |
|
||||
| complete | 完成回调函数 | _(res: any) => void_ | - |
|
||||
|
||||
## 使用注意事项
|
||||
|
||||
1. APP平台下函数是同步的,返回结果直接使用
|
||||
2. 非APP平台(如H5、小程序)下函数是异步的,返回Promise
|
||||
3. 在条件编译中需要注意区分平台差异
|
||||
4. dataURLToFile函数的filename参数是可选的,如不提供会自动生成临时文件名
|
||||
5. 处理大文件时可能会占用较多内存,请注意性能影响
|
||||
|
||||
## 平台差异说明
|
||||
|
||||
| 函数 | APP | H5 | 微信小程序 | 其他小程序 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| fileToDataURL | 同步 | 异步 | 异步 | 异步 |
|
||||
| fileToBase64 | 同步 | 异步 | 异步 | 异步 |
|
||||
| dataURLToFile | 同步 | 异步 | 异步 | 异步 |
|
||||
| processFile | 支持 | 支持 | 支持 | 支持 |
|
||||
|
||||
## 支持与赞赏
|
||||
|
||||
如果你觉得本插件解决了你的问题,可以考虑支持作者:
|
||||
|
||||
| 支付宝赞助 | 微信赞助 |
|
||||
|------------|------------|
|
||||
|  |  |
|
||||
@@ -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