uni_android_plugin_project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

398 lines
12 KiB

3 years ago
  1. /*
  2. *V1.0
  3. *基于5+ IO 封装的基础文件操作库
  4. *更新日期:2022/06/09
  5. */
  6. let downloadTask;
  7. async function readLocal(){
  8. let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
  9. let mFileEntry = await getDirectory({
  10. OriginPathEntry: fs.root,
  11. newFileName: 'OXSyncConfig'
  12. });
  13. let mConfigEntry = await mGetFile(mFileEntry,"config.json")
  14. let mReadResult = await mFile(mConfigEntry)
  15. console.log("读取结果:",mReadResult);
  16. return mReadResult
  17. }
  18. async function writeLocal(msg){
  19. let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
  20. let mFileEntry = await getDirectory({
  21. OriginPathEntry: fs.root,
  22. newFileName: 'OXSyncConfig'
  23. });
  24. let mConfigEntry = await mGetFile(mFileEntry,"config.json")
  25. // console.log(mConfigEntry.fullPath);
  26. let mWriteResult = await mCreateWriter(mConfigEntry,msg)
  27. console.log("写入结果:",mWriteResult);
  28. return mWriteResult
  29. }
  30. async function writeLocalOld(msg){
  31. //存储信息到本地,如没有文件,则创建, 有则读取存入
  32. let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
  33. let mFileEntry = await getDirectory({
  34. //在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
  35. OriginPathEntry: fs.root,
  36. newFileName: 'OXSyncConfig'
  37. });
  38. // let newNameFileEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + newName).catch(e => {
  39. // console.log('目标文件可以操作', e);
  40. // });
  41. let savedFilePathEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + "config.json"); //获取下载后存储的文件Entry
  42. let write_result = writeFile(mFileEntry,"config.json",msg)
  43. console.log(9999,JSON.stringify(write_result))
  44. }
  45. async function readLocalOld(){
  46. // 读取本地文件
  47. console.log("readLocal begin")
  48. let newName = "oxconfig.txt"
  49. let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
  50. let mFileEntry = await getDirectory({
  51. //在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
  52. OriginPathEntry: fs.root,
  53. newFileName: 'OXSyncConfig'
  54. });
  55. let newNameFileEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + newName).catch(e => {
  56. console.log('目标文件可以操作', e);
  57. });
  58. if (newNameFileEntry) {
  59. console.log("配置文件已存在准:",newNameFileEntry.fullPath)
  60. // return newNameFileEntry.fullPath //返回已缓存文件路径
  61. }
  62. // mFileEntry是操作对象DirectoryEntry
  63. let result = getFile(mFileEntry,"config.json")
  64. console.log("result: "+JSON.stringify(result))
  65. }
  66. //下载数据,当有缓存时直接使用
  67. //item.url 下载地址
  68. //item.name 文件名
  69. //item.forceDownload 当本地存在缓存时,是否强制删除后重新下载
  70. //item.deleteFile 仅删除文件名为item.name 的文件
  71. async function adDownloadFileAuto(item) {
  72. let fs = await download.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
  73. let url = item.url; //测试url---------
  74. let newName = item.name;
  75. let faceSyncEntry = await download.getDirectory({
  76. //在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
  77. OriginPathEntry: fs.root,
  78. newFileName: 'ad'
  79. });
  80. let newNameFileEntry = await download.resolveLocalFileSystemURL(faceSyncEntry.fullPath + newName).catch(e => {
  81. console.log('目标文件可以操作', e);
  82. });
  83. if (newNameFileEntry) {
  84. console.log('存在缓存的同名文件:', newNameFileEntry.fullPath);
  85. if(item.deleteFile){
  86. let delResult = await download.removeFile(newNameFileEntry); //删除已存在的文件
  87. console.log("删除同名文件结果:",delResult)
  88. return delResult
  89. }
  90. if(item.forceDownload){//当本地存在缓存时,是否强制删除后重新下载
  91. let delResult = await download.removeFile(newNameFileEntry); //删除已存在的文件
  92. }else{
  93. return newNameFileEntry.fullPath //返回已缓存文件路径
  94. }
  95. }
  96. let onProgresCallBack = function(e) {
  97. //预留下载进度封装拓展
  98. // console.log('下载中...', url, e);
  99. };
  100. let tempDownloadFilePath = await download.getDownloadFile({ url, onProgresCallBack }); //获取下载文件临时路径
  101. let savedFilePath = await download.getSaveFile(tempDownloadFilePath); //将文件临时路径长久存储并清除
  102. // let newName = item.user_id + '.' + (adType); //命名与android约定的文件名: [user_id].jpg------------
  103. // newName = item.user_id + this.getName(url);
  104. console.log(tempDownloadFilePath, 123456, savedFilePath.split('.')[1], savedFilePath);
  105. let savedFilePathEntry = await download.resolveLocalFileSystemURL(savedFilePath); //获取下载后存储的文件Entry
  106. let reNamePathEntry = await download.moveFileTo(savedFilePathEntry, faceSyncEntry, newName); //重命名文件到人脸库同步文件夹
  107. // console.log(666,savedFilePath,newName,reNamePathEntry.fullPath)
  108. return reNamePathEntry.fullPath;
  109. }
  110. function getDownloadFile({
  111. url,
  112. onProgresCallBack
  113. }) {
  114. return new Promise((rs, rj) => {
  115. if (downloadTask) downloadTask.abort();
  116. downloadTask = uni.downloadFile({
  117. url: url,
  118. timeout:60000,
  119. // header:{
  120. // "content-type":"image/png"
  121. // },
  122. success: res => {
  123. if (res.statusCode == 200) {
  124. console.log(url+" downloadFile:"+JSON.stringify(res))
  125. rs(res.tempFilePath)
  126. } else {
  127. console.warn('下载失败--->', res);
  128. console.warn('下载失败链接--->', url);
  129. rj(res)
  130. }
  131. },
  132. fail: failRes => {
  133. console.warn('下载失败--->', failRes);
  134. console.warn('下载失败链接--->', url);
  135. rj(failRes)
  136. }
  137. })
  138. downloadTask.onProgressUpdate(res => {
  139. onProgresCallBack && onProgresCallBack(res);
  140. })
  141. })
  142. }
  143. //从临时路径文件获取持久文件
  144. function getSaveFile(url) {
  145. return new Promise((rs, rj) => {
  146. uni.saveFile({
  147. tempFilePath: url,
  148. success: function(res_save) {
  149. var savedFilePath = res_save.savedFilePath; //相对路径
  150. // var absFilePath = plus.io.convertLocalFileSystemURL(savedFilePath); //绝对路径
  151. // console.log('相对路径: ' + savedFilePath);
  152. // console.log("绝对路径: " + absFilePath);
  153. rs(savedFilePath)
  154. // uni.getSavedFileList({
  155. // success: function (res) {
  156. // console.log(res.fileList);
  157. // }
  158. // });
  159. },
  160. fail: function(e) {
  161. rj(e);
  162. }
  163. });
  164. })
  165. }
  166. //根据本地文件url转换为fileEntry
  167. function resolveLocalFileSystemURL(FilefullPath) {
  168. return new Promise((rs, rj) => {
  169. plus.io.resolveLocalFileSystemURL(FilefullPath,
  170. function(fs) {
  171. rs(fs)
  172. },
  173. function(err) {
  174. rj(err)
  175. });
  176. })
  177. }
  178. // 请求本地文件系统对象Entry
  179. // type:
  180. // 应用私有资源目录,对应常量plus.io.PRIVATE_WWW,仅应用自身可读
  181. // 应用私有文档目录,对应常量plus.io.PRIVATE_DOC,仅应用自身可读写
  182. // 应用公共文档目录,对应常量plus.io.PUBLIC_DOCUMENTS,多应用时都可读写,常用于保存应用间共享文件
  183. // 应用公共下载目录,对应常量plus.io.PUBLIC_DOWNLOADS,多应用时都可读写,常用于保存下载文件
  184. //fs.root 为相应Entry
  185. function requestFileSystem(type) {
  186. return new Promise((rs, rj) => {
  187. plus.io.requestFileSystem(type,
  188. function(fs) {
  189. rs(fs)
  190. },
  191. function(err) {
  192. rj(err)
  193. });
  194. })
  195. }
  196. //移动文件(重命名)
  197. function moveFileTo(fromPathEntry, toPathEntry, newFileName) {
  198. return new Promise((rs, rj) => {
  199. // remove this directory
  200. // entry.remove( function ( entry ) {
  201. // plus.console.log( "Remove succeeded" );
  202. // }, function ( e ) {
  203. // alert( e.message );
  204. // } );
  205. fromPathEntry.moveTo(toPathEntry, newFileName, function(entry) {
  206. // console.log("新文件路径: " + entry.fullPath);
  207. rs(entry)
  208. }, function(e) {
  209. console.log(e.message);
  210. rj(e);
  211. });
  212. })
  213. }
  214. // 删除文件
  215. function removeFile(entry){
  216. // return new Promise(rs=>entry.remove( rs, rs ))
  217. return new Promise((rs,rj)=>{
  218. entry.remove( function ( entry ) {
  219. console.log(entry)
  220. rs( "Remove succeeded: "+entry.name );
  221. }, function ( e ) {
  222. rj( e.message );
  223. } );
  224. })
  225. }
  226. // 递归删除目录
  227. function removeFileAll(entry){
  228. return new Promise(rs=>entry.removeRecursively( rs, rs ))
  229. }
  230. //创建,读取文件
  231. // 废弃
  232. // function getFile(mFileEntry,path){
  233. // // entry.getFile( path, flag, succesCB, errorCB );
  234. // mFileEntry.getFile(path,{create:true}, function(fileEntry){
  235. // fileEntry.file( function(file){
  236. // var fileReader = new plus.io.FileReader();
  237. // console.log("getFile:" + JSON.stringify(file));
  238. // fileReader.readAsText(file, 'utf-8');
  239. // fileReader.onloadend = function(evt) {
  240. // console.log("evt:" + evt);
  241. // console.log("evt.target" + evt.target);
  242. // console.log(evt.target.result);
  243. // rs(evt.target.result)
  244. // }
  245. // console.log( ">>>>>>>文件信息:"+file.name + ' : ' + file.size +" Kb <<<<<<<<");
  246. // } );
  247. // });
  248. // }
  249. // //废弃
  250. // function writeFile(mFileEntry,path,msg){
  251. // // Write data to file
  252. // mFileEntry.getFile(path,{create:true}, function(fileEntry){
  253. // fileEntry.createWriter( function ( writer ) {
  254. // writer.onwrite = function ( e ) {
  255. // console.log( "Write data success!" );
  256. // rs(true)
  257. // };
  258. // // Write data to the end of file.
  259. // // writer.seek( writer.length );
  260. // writer.write(JSON.stringify(msg));
  261. // }, function ( e ) {
  262. // console.log( e.message );
  263. // rj(false)
  264. // } );
  265. // });
  266. // }
  267. //获取file Entry
  268. function mGetFile(mFileEntry,path){
  269. return new Promise((rs,rj)=>{
  270. mFileEntry.getFile(path,{create:true}, function(fileEntry){
  271. rs(fileEntry)
  272. });
  273. })
  274. }
  275. //获取操作file
  276. function mFile(fileEntry){
  277. return new Promise((rs,rj)=>{
  278. fileEntry.file( function(file){
  279. var fileReader = new plus.io.FileReader();
  280. // console.log("getFile:" + JSON.stringify(file));
  281. fileReader.readAsText(file, 'utf-8');
  282. fileReader.onloadend = function(evt) {
  283. // console.log("evt:" + evt);
  284. // console.log("evt.target" + evt.target);
  285. // console.log(evt.target.result);
  286. rs(evt.target.result)
  287. }
  288. console.log( ">>>>>>>文件信息:"+file.name + ' : ' + file.size +" B <<<<<<<<"+ JSON.stringify(file));
  289. } );
  290. })
  291. }
  292. //读取文件
  293. function mCreateReader(fileEntry){
  294. return new Promise((rs,rj)=>{
  295. fileEntry.createWriter( function ( writer ) {
  296. writer.onwrite = function ( e ) {
  297. console.log( "Write data success!" );
  298. rs("success")
  299. };
  300. // Write data to the end of file.
  301. // writer.seek( writer.length );
  302. writer.write(JSON.stringify(msg));
  303. }, function ( e ) {
  304. console.log( e.message );
  305. rj(e.message)
  306. } );
  307. })
  308. }
  309. //写入文件
  310. function mCreateWriter(fileEntry,msg){
  311. return new Promise((rs,rj)=>{
  312. fileEntry.createWriter( function ( writer ) {
  313. writer.onwrite = function ( e ) {
  314. console.log( "Write data success!" );
  315. rs("success")
  316. };
  317. // Write data to the end of file.
  318. // writer.seek( writer.length );
  319. writer.write(JSON.stringify(msg));
  320. }, function ( e ) {
  321. console.log( e.message );
  322. rj(e.message)
  323. } );
  324. })
  325. }
  326. // 从父目录下创建或打开子目录
  327. function getDirectory({
  328. OriginPathEntry,
  329. newFileName
  330. }) {
  331. return new Promise((rs, rj) => {
  332. // Retrieve an existing directory, or create it if it does not already exist
  333. OriginPathEntry.getDirectory(newFileName, {
  334. create: true,
  335. exclusive: false
  336. }, function(dir) {
  337. // console.log("Directory Entry Name: " + dir.name);
  338. rs(dir)
  339. }, function(e) {
  340. console.log(dir.name,e.message);
  341. rj(e)
  342. });
  343. })
  344. }
  345. //获取该DirectoryEntry下所有文件和子目录
  346. function getFileChildrenList(DirectoryEntry){
  347. return new Promise((rs, rj) => {
  348. // 创建读取目录信息对象
  349. var directoryReader = DirectoryEntry.createReader();
  350. directoryReader.readEntries( function( entries ){
  351. var i,res=[];
  352. for( i=0; i < entries.length; i++ ) {
  353. // console.log( entries[i].name );
  354. res.push( entries[i].name)
  355. }
  356. rs(res)
  357. }, function ( e ) {
  358. console.log( "Read entries failed: " + e.message );
  359. rj(e.message)
  360. } );
  361. })
  362. }
  363. module.exports = {
  364. getSaveFile,
  365. getDownloadFile,
  366. requestFileSystem,
  367. resolveLocalFileSystemURL,
  368. moveFileTo,
  369. getDirectory,
  370. removeFile,
  371. removeFileAll,
  372. readLocal,
  373. writeLocal,
  374. getFileChildrenList
  375. }