[uniapp] 文件系统操作

 在使用uniapp进行ios和android开发时,有可能需要对文件进行操作,比如:创建文件夹和文件,删除文件等。这些操作必须调用plus.io相关的API才行,并且这些API是都异步操作的,在我们的业务中,有时又必须同步处理才行,所以我将所有的操作进行了同步化的处理,将代码抽到一个名为IoUtil.js的文件中,通过ES6的方式导出方法,然后在vue文件中直接导入使用即可。代码如下,代码分为同步和异步两部分,各自根据需要使用即可:

IoUtil.js

// -------------------------------------默认的异步操作------------------------------
export function getDirectory(directoryName,successCB){
	plus.io.requestFileSystem( 
		plus.io.PRIVATE_DOC, 
		function( fs ) {
			//directoryName:可以是一个文件名,如果是路径,则路径上的所有文件夹都会自动创建
			fs.root.getDirectory(directoryName, {create:true},successCB, function(){} );
			console.log("创建完成.............")
		}, 
		function ( e ) {} 
	);
}

export function getFile(filePath,successCB){
	plus.io.requestFileSystem( 
		plus.io.PRIVATE_DOC, 
		function( fs ) {
			//directoryName:可以是一个文件名,如果是路径,则路径上的所有文件夹都会自动创建
			fs.root.getFile(filePath, {create:true},successCB, function(){} );
			console.log("创建完成.............")
		}, 
		function ( e ) {} 
	);
}

export function moveFile(srcFilePath,srcFileName,dstFilePath,dstFileName,successCB){
	plus.io.resolveLocalFileSystemURL( "_documents/b1/bridges.json", function( entry ){
		plus.io.resolveLocalFileSystemURL("_doc/", function(root){
			/* entry.copyTo( 
				root, 
				"bridges11.json", 
				function( entry ){
					console.log("New Path: " + entry.fullPath);
				},
				function( e ){
					console.log( "错1误"+JSON.stringify(e) );
				}
			); */
			entry.moveTo(
				root, 
				"bridges12.json", 
				function( entry ){
					console.log("New Path: " + entry.fullPath);
				},
				function( e ){
					console.log( "错1误"+JSON.stringify(e) );
				}
			); 
		})
	})
}

export function copyFile(srcFilePath,srcFileName,dstFilePath,dstFileName,successCB){
	plus.io.resolveLocalFileSystemURL( "_documents/b1/bridges.json", function( entry ){
		plus.io.resolveLocalFileSystemURL("_doc/", function(root){
			entry.copyTo( 
				root, 
				"bridges11.json", 
				function( entry ){
					console.log("New Path: " + entry.fullPath);
				},
				function( e ){
					console.log( "错1误"+JSON.stringify(e) );
				}
			);
		})
	})
}

/**
 * 传入目录dirEntry,如果传了fileName,则删除对应文件,否则目录下所有文件全部删除
 * @param {Object} dirEntry
 * @param {Object} fileName
 */
export function removeFile(dirEntry, fileName) {
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		let entry = dirEntry || fs.root;
		let directoryReader = entry.createReader();
		directoryReader.readEntries(function(entries) {
			for (let i = entries.length - 1; i >= 0; i--) {
				if (fileName) {
					if (fileName === entries[i].name) {
						console.log("删除文件", entries[i].name);
						entries[i].remove();
					}
				} else {
					entries[i].remove();
				}
			}
		});
	});
}


// ----------------------------------------------------------------同步化-操作-----------------------------------------
/**
 * 同步化获取文件,文件不存在会自动创建
 * @param {Object} fileName 可以是文件名,也可以是/路径/文件名
 * @param {Object} dirEntry
 * @return 文件Entry
 */
export async function getFileEntryAsync(fileName,dirEntry){
	console.log("[getFileEntryAsync]开始执行")
	return new Promise((resolve) => {
		plus.io.requestFileSystem(
			plus.io.PRIVATE_DOC, 
			function(fs) {
				console.log("[getFileEntryAsync]fileName is :" + fileName)
				let entry = dirEntry || fs.root;
				entry.getFile(
					fileName, {create: true}, 
					function(fileEntry) {
						console.log("[getFileEntryAsync] 执行完成")
						resolve(fileEntry);
					},function(ex){console.log(ex)}
				);
			}
		);
	})
}

/**
 * 获取文件夹,不存在会自动创建
 * @param {Object} dirName 
 */
export async function getDirEntryAsync(dirName) {
	return new Promise(async (resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			fs.root.getDirectory(dirName, {
				create: true
			}, function(dirEntry) {
				resolve(dirEntry);
			})
		})
	})
}

/**
 * 获取通过fileEntry获取file,不存在会自动创建
 * @param {Object} fileName
 * @param {Object} dirEntry
 */
export async function getFileAsync(fileName, dirEntry) {
	console.log("[getFileAsync]")
	return new Promise(async (resolve) => {
		let fileEntry = await getFileEntryAsync(fileName, dirEntry);
		fileEntry.file(function(file) {
			resolve(file);
		});
	})
}

/**
 * 读取文件中的内容
 * @param {Object} path
 * @param {Object} dirEntry
 */
export async function getFileContextAsync(path, dirEntry) {
	let deffered;
	let fileReader = new plus.io.FileReader();
	fileReader.onloadend = function(evt) {
		deffered(evt.target);
	}
	let file = await getFileAsync(path, dirEntry);
	fileReader.readAsText(file, 'utf-8');
	return new Promise((resolve) => {
		deffered = resolve;
	});
}

/**
 * 向文件中写入数据
 * @param {Object} path 要写入数据的文件的位置
 * @param {Object} fileContext 要写入的内容
 * @param {Object} dirEntry 文件夹,可不写使用默认
 */
export async function writeContextToFileAsync(path,fileContext, dirEntry) {
	let fileEntry =await getFileEntryAsync(path);
	let file =await getFileAsync(path);
	return new Promise((resolve) => {
		fileEntry.createWriter( async writer => {
			// 写入文件成功完成的回调函数
			writer.onwrite = e => {
				console.log("写入数据成功");
				resolve()
			};
			  // 写入数据
			writer.write(JSON.stringify(fileContext));
		})
	});
}

/**
 * 判断文件是否存在
 * @param {Object} fileName
 * @param {Object} dirEntry
 */
export async function existFileAsync(fileName, dirEntry){
	return new Promise((resolve)=>{
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root;
			let directoryReader = entry.createReader();
			directoryReader.readEntries(function(entries) {
				let isExist = entries.some(entry => entry.name === fileName);
				resolve(isExist);
			});
		});
	})
}

/**
 * 遍历dirEntry,深层次的目录暂不考虑
 * @param {Object} dirEntry
 */
export async function iterateDierctory(dirEntry) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root;
			let directoryReader = entry.createReader();
			directoryReader.readEntries(function(entries) {
				entries.forEach((item, idx, arr)=>{
					if(idx===0) console.log("---------------"+entry.name+"目录-----------------");
					console.log(idx+1, item.name);
					if(idx===arr.length-1) console.log("---------------end-----------------");
				})
				resolve(entries);
			}, function(e) {
				console.log("Read entries failed: " + e.message);
			});
		});
	})
}

/* 调用例子
this.DIR_NAME = 'test'
fileName = 'test.json'
filePath = '_doc/test/test.json'
let dirEntry = await this.getDirEntry(this.DIR_NAME); //创建、获取文件夹
let fileEntry = await this.getFileEntry(fileName, dirEntry); // 创建、获取文件
let {result:content} = await this.getFileContext(filePath); // 获取文件的内容
let trajectory = JSON.parse(content||"[]");
trajectory.push({lat, lng});
fileEntry.createWriter(function(writer){
	writer.seek(0);
	writer.write(JSON.stringify(trajectory));
}); */

有了同步化的方法后,在vue问价中写业务时就不需要使用回调方法或者then了。

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值