Uniapp 中的plus.io如何存储文件

IO模块管理本地文件系统,用于对文件系统的目录浏览、文件的读取、文件的写入等操作。通过plus.io可获取文件系统管理对象

5+ API在系统应用目录的基础设计了应用沙盒目录, 分为私有目录公共目录两种类型,

应用私有资源目录,对应常量plus.io.PRIVATE_WWW,仅应用自身可读
应用私有文档目录,对应常量plus.io.PRIVATE_DOC,仅应用自身可读写
应用公共文档目录,对应常量plus.io.PUBLIC_DOCUMENTS,多应用时都可读写,常用于保存应用间共享文件
应用公共下载目录,对应常量plus.io.PUBLIC_DOWNLOADS,多应用时都可读写,常用于保存下载文件

常量:
PRIVATE_WWW: 应用私有资源目录常量
PRIVATE_DOC: 应用私有文档目录常量
PUBLIC_DOCUMENTS: 应用公共文档目录常量
PUBLIC_DOWNLOADS: 应用公共下载目录常量

方法:
requestFileSystem: 请求本地文件系统对象
resolveLocalFileSystemURL: 通过URL参数获取目录对象或文件convertLocalFileSystemURL: 将本地URL路径转换成平台绝对路径
convertAbsoluteFileSystem: 将平台绝对路径转换成本地URL路
getAudioInfo: 获取音频文件信息
getFileInfo: 获取文件信息
getImageInfo: 获取图片信息
getVideoInfo: 获取视频文件信息

在uniapp项目中的utils自定义一个js文件,

file.js

// 读取json文件
function getJsonData(path) { //path:路径
	console.log("getData");
	return new Promise(resolve => { //文件读写是一个异步请求 用promise包起来方便使用时的async+await
		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => { //请求文件系统
				fs.root.getFile(
					path, { //请求地址文件  '/storage/emulated/0/config.txt'为根目录  '/config.txt'为/storage/Android/data/io.dcloud.HBuilder(包名)/documents/config.js
						create: true //当文件不存在时创建
					}, fileEntry => {
						fileEntry.file(function(file) {
							let fileReader = new plus.io
								.FileReader(); //new一个可以用来读取文件的对象fileReader
							fileReader.readAsText(file, "utf-8"); //读文件的格式
							fileReader.onerror = e => { //读文件失败
								console.log("获取文件失败", fileReader.error);
								plus.nativeUI.toast("获取文件失败,请重启应用", {
									background: "rgba(255, 255, 255, 0.6)",
								});
								return;
							};
							fileReader.onload = e => { //读文件成功
								console.log("读取文件成功");
								let txtData = e.target.result;
								// console.log(txtData);
								resolve(txtData); //回调函数内的值想返回到函数外部  就用promise+resolve来返回出去
							};
						});
					}, error => {
						console.log("2新建获取文件失败", error);
						plus.nativeUI.toast("获取文件失败,请重启应用", {
							background: "rgba(255, 255, 255, 0.6)",
						});
						return;
					});
			},
			e => {
				console.log("1请求文件系统失败", e.message);
				plus.nativeUI.toast("请求系统失败,请重启应用", {
					background:  "rgba(255, 255, 255, 0.6)",
				});
				return;
			}
		);
	});
};
// 写入josn文件
function changeData(path, seek, writeData) { //参数1:上传路径,参数2:seek方法可设置文件操作指定位置,参数3:写入的json数据
	return new Promise(resolve => {
		// resolveLocalFileSystemURL  requestFileSystem  PUBLIC_DOCUMENTS PRIVATE_DOC
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, fs => {
			fs.root.getFile(path, {
					create: true
				}, fileEntry => {
					fileEntry.file(file => {
						fileEntry.createWriter(writer => {
							 console.log( fs.root.toURL(),'路径111')
								plus.nativeUI.showWaiting("正在保存信息");
								writer.seek(seek); //覆盖文件
								const writeDataTemp = JSON.stringify(writeData, null,
									"\r").replace(/[\r]/g, "");
								writer.write(writeDataTemp); // 整个文件重写
								writer.onerror = function() {
									console.log("4写入文件失败", writer.error.message);
									plus.nativeUI.closeWaiting();
									plus.nativeUI.toast("修改信息失败,请重新操作", {
										background: "rgba(255, 255, 255, 0.6)",
									});
									return;
								};
								writer.onsuccess = function() { //填写文件成功
								
									plus.nativeUI.closeWaiting();
									plus.nativeUI.toast("保存成功", {
										// background: "rgba(255, 255, 255, 0.6)",
									});
									resolve("1");
								};
							},
							error => {
								console.log("3创建creactWriter失败", error);
								plus.nativeUI.toast("保存文件失败,请重新操作", {
									// background: "#ffa38c",
								});
								return;
							});
					});
				},
				error => {
					console.log("2获取文件失败", error);
					plus.nativeUI.toast("保存文件失败,请重新操作", {
						// background: "#ffa38c",
					});
					return;
				}
			);
		}, e => {
			console.log("1请求文件系统失败", e.message);
			plus.nativeUI.toast("请求系统失败,请重新操作", {
				// background: "#ffa38c",
			});
			return;
		});
	});
}
/**
 * 储存文件到指定的地址:把一个文件移动到另外一个位置 剪切文件 重命名文件
 * @param {String} url				 	新的地址 _doc/ 开头
 * @param {String} file                	原文件地址
 * @param {String} newfilename 			新的文件名
 */
async function saveFile(url, file, newfilename) {
	let c = await creatDirs(url)
	let isokm = moveDirectyOrFile(file, url + "/", newfilename);
	return isokm
}
//循环创建目录 url:"_doc/...."  _doc开头
async function creatDirs(url) {
	let urllist = url.split("/");
	console.log(urllist)
	//创建文件夹
	let u = "";
	for (let i = 0; i < urllist.length - 1; i++) {
		let j = i;
		if (i == 0) {
			u = urllist[i];
		} else {
			u = u + "/" + urllist[i];
		}
		console.log(i + "-------------------")
		console.log(u)
		console.log(urllist[j + 1])
		await CreateNewDir(u, urllist[j + 1]);
	}
}
//重命名目录或文件名
function moveDirectyOrFile(srcUrl, dstUrl, newName) { //srcUrl需要移动的目录或文件,dstUrl要移动到的目标目录(父级)
	plus.io.resolveLocalFileSystemURL(srcUrl, function(srcEntry) {
		//console.log(111)
		plus.io.resolveLocalFileSystemURL(dstUrl, function(dstEntry) {
			//console.log(222)
			if (srcEntry.isDirectory) {
				//console.log(33)
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			} else {
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			}
		}, function(e) {
			uni.showToast({
				title: '获取目标目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	}, function(e) {
		uni.showToast({
			title: '获取目录失败:' + e.message,
			duration: 2000,
			icon: 'none'
		});
	});
}

//创建一个新目录
function CreateNewDir(url, dirName) {
	//url值可支持相对路径URL、本地路径URL
	return new Promise((resolver, reject) => {
		plus.io.resolveLocalFileSystemURL(url, function(entry) {
			entry.getDirectory(dirName, {
				create: true,
				exclusive: false
			}, function(dir) {
				resolver(true)
			}, function(error) {
				reject(error.message)
				uni.showToast({
					title: dirName + '目录创建失败:' + error.message,
					duration: 2000,
					icon: 'none'
				});
			});
		}, function(e) {
			reject(error.message)
			uni.showToast({
				title: '获取目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	})
}
/**
 * 复制文件
 * @param {String} url        文件地址,文件路径,最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newUrl     目标目录,最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newName    拷贝后的文件名称,默认为原始文件名称
 */
function copyFileTo(url, newUrl, dirName, newName) {
	if (url.length >= 7 && "file://" == url.substring(0, 7)) {
		url = url.substring(7)
	}
	let tempUrl = url.substring(0, url.lastIndexOf('/'));
	let addUrl = newUrl + '/' + dirName;
	console.log(addUrl, tempUrl)
	if (addUrl == tempUrl) {
		return url;
	}
	console.log(newUrl, dirName, newName)
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, async (entry) => {
			if (entry.isFile) {
				let c = await CreateNewDir(newUrl, dirName)
				let u = await getDirsys(addUrl)
				entry.copyTo(u, newName, en => {
					resolve(en.fullPath);
				}, e => {
					console.log(e);
					reject('错误:复制时出现错误')
					uni.showModal({
						title: "错误",
						content: "复制时出现错误"
					})
				})
			} else {
				reject('错误:路径必须是文件')
				uni.showModal({
					title: "错误",
					content: "路径必须是文件"
				})
			}
		}, (e) => {
			console.log(e);
			reject(e)
			uni.showModal({
				title: "错误",
				content: "打开文件系统时出错"
			})
		});
	})
}
//获取目录对象
function getDirsys(url) {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, (entry) => {
			resolve(entry)
		}, (e) => {
			reject(e)
			console.log(e);
		});
	})
}
//将这些方法暴露出去
export {
	getJsonData,
	changeData,
	saveFile,
	creatDirs,
	moveDirectyOrFile,
	copyFileTo,
	getDirsys,
};

然后在pages中页面,引入file.js

<template>
	<view>
	</view>
</template>

<script>
	import {
		getJsonData,
		changeData
	} from '@/utils/file.js';
	export default {
		data() {
			return {
				Name: 'config'
			}
		},
		onLoad() {
			//兼容安卓10+ (通用)
			const pathUrl = plus.io.convertLocalFileSystemURL("_downloads/") + this.Name + '.json'
			//安卓10以下路径地址  
			const pathUrl2 = '/storage/emulated/0/' + this.Name + '.json'
			//安卓10+	pathUrl2  会报targetSdkVersion设置>=29后在Android10+系统设备不支持当前路径。请更改为应用运行路径 
			const data = [{
					"name": "Bob",
					"gender": "male",
					"birthday": "1992-10-18",
					"url": 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pptbz.com%2Fd%2Ffile%2Fp%2F201708%2Fb92908f5427aaa3dc10aea19c06e013d.jpg&refer=http%3A%2F%2Fwww.pptbz.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1665027371&t=951dc21337ec50fdf056325b579af716'
				},
				{
					"name": "Selina",
					"gender": "female",
					"birthday": "1995-11-16"
				}
			]
			changeData(pathUrl, 0, data); //上传路径,0,全局变量数据

		},
		methods: {
		}
	}
</script>

我在引入file.js,然后在onload()函数配置json文件的路径,

const pathUrl2 = ‘/storage/emulated/0/’ + this.Name + ‘.json’
const pathUrl = plus.io.convertLocalFileSystemURL(“_downloads/”) +
this.Name + ‘.json’

const data = [{
					"name": "Bob",
					"gender": "male",
					"birthday": "1992-10-18",
					"url": 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.pptbz.com%2Fd%2Ffile%2Fp%2F201708%2Fb92908f5427aaa3dc10aea19c06e013d.jpg&refer=http%3A%2F%2Fwww.pptbz.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1665027371&t=951dc21337ec50fdf056325b579af716'
				},
				{
					"name": "Selina",
					"gender": "female",
					"birthday": "1995-11-16"
				}
			]

这个加载页面会创建config.json,data是引入的数据,你可以引入数据、图片路径、视频、文件等

再调用changeData(pathUrl, 0, data); //上传路径,0,全局变量数据可以在手机查看到数据
在这里插入图片描述
在这里插入图片描述
config.json的数据
在这里插入图片描述

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@逆风boy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值