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.

391 lines
12 KiB

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