uniapp iosApp H5+本地文件操作(写入修改删除等)

h5+ 地址 html5plus

以csv文件为例,写入读取保存修改删除文件内容,传输文件等

1.save 文件保存

typescript 复制代码
function saveCsv(data,pathP,path){
	// #ifdef APP-PLUS
	return new Promise((resolve, reject) => {
		plus.io.requestFileSystem( plus.io.PUBLIC_DOCUMENTS, function( fs ) {
			// 通过fs.root获取DirectoryEntry对象进行操作
			 fs.root.getDirectory(pathP,{create:true},direEntry =>{
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
					fs.root.getFile(path, {create: true}, fileEntry => {
						fileEntry.createWriter(writer => {
							writer.onwrite = e => {
								resolve(`file://${e.target.fileName}`);
								// uni.showModal({
								// 	title: '提示',
								// 	content: `导出成功,文件路径为${e.target.fileName.replace('/storage/emulated/0', '')}`,
								// 	cancelText: '了解并关闭',
								// 	confirmText: '预览文件',
								// 	success: result => {
								// 		if (result.confirm) {
								// 			uni.openDocument({
								// 				filePath: `file://${e.target.fileName}`,
								// 			})
								// 		}
								// 	}
								// });
							}
							writer.write(data);
						}, writerErr => {
							resolve(500)
							uni.showToast({
								title: '导出文件失败,请检查是否有权限',
								icon: 'none'
							});
						})
					})
				})
			})
		}, fsErr => {
			uni.showToast({
				title: '导出文件失败,请检查是否有权限',
				icon: 'none'
			});
		})
	})
	// #endif	
}

// #ifdef APP-PLUS
let submitCsv = savedata.map(e=> JSON.stringify(e)).join("\n");
saveCsv(submitCsv,`${user}/triallist/${_this.trialId}`,`${user}/triallist/${_this.trialId}/scoresubmit.csv`).then(path=>{
	console.log(path)
})
// #endif

2. read 读取

typescript 复制代码
function readListCsv(path){
	let reader = null;
	let data=[];
	// #ifdef APP-PLUS
	return new Promise((resolve, reject) => {
		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS,fs => {
			fs.root.getFile(path,{create:true},fileEntry=> {
				fileEntry.file( function ( file ) {
					reader = new plus.io.FileReader();
					reader.onloadend = function ( e ) {
						if(e.target.result){
						  //返回的data处理取决于存入时的操作,不同格式不同操作
							data = e.target.result.split('\n').map(e=> JSON.parse(e))
							resolve(data);
						}else{
							data = []
							resolve(data);
						}
					};
					reader.readAsText( file );
				}, function ( e ) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					});
				});
			})
		})
	})
	// #endif
}

// #ifdef APP-PLUS
//自定义文件路径
readListCsv(`${user}/triallist/${this.trialId}/time.csv`).then(res=>{
	console.log(res)
})

3. delete 删除目录

typescript 复制代码
//已存在目录,删除重建
let path = uni.getStorageSync('path') + `/${user}/triallist/${_this.trialId}`;
plus.io.resolveLocalFileSystemURL(path, function( entry ) {
	let directoryReader = entry.createReader(); //获取读取目录对象
	directoryReader.readEntries( function( entries ){
		console.log(entries.length);
		if (entries.length > 0) {
			 entry.removeRecursively(function(entry) {
				 callback();
				 //删除成功回调---获取不到。。。。    
			 }, function(e) {
				 //错误信息    
				 console.log(e.message + ' ?!')
			 })
		}
	})
})

4.upload 上传(uniapp)循环上传目录内文件

typescript 复制代码
// #ifdef APP-PLUS
//使用uniapp上传需要上传文件获取uniapp生成的路径后,调用上传接口
updateResume(){
	let path = uni.getStorageSync('path') + `/${user}/triallist/${this.trialId}/......`
	plus.io.resolveLocalFileSystemURL(path, function( entry ) {
		var directoryReader = entry.createReader(); //获取读取目录对象
		directoryReader.readEntries( function( entries ){
			for(let i=0; i < entries.length; i++ ){
				uni.saveFile({
					tempFilePath: path + entries[i].name,
					success: function (res) {
						uni.uploadFile({
							url:NEV.BASE_URL +'/api/api..../add',
							filePath:res.savedFilePath,
							header: {
								'X-Access-Token':uni.getStorageSync('token'),
								'Authorization': 'Bearer ' + uni.getStorageSync('token'),
								"Content-Type": "multipart/form-data",
							},
							name:'MultipartFile',
							formData: {  //接口携带的参数
								trialId:_this.trialId,
							},
							success() {
								console.log('一个文件上传成功');
							},
							fail() {
								console.log('一个文件上传失败');
							}
						})
					},
					fail() {
						console.log('一个文件上传失败');
					}
				});
				console.log( entries[i].name );
			}
		}, function ( e ) {
			alert( "Read entries failed: " + e.message );
		} );
	});
	// #endif
}
相关推荐
2501_915909061 小时前
iOS APP 抓包全流程解析,HTTPS 调试、网络协议分析与多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 小时前
游戏上架 App Store 的技术流程解析 从构建到审核的全流程指南
游戏·macos·ios·小程序·uni-app·cocoa·iphone
行云流水62611 小时前
uniapp pinia实现数据持久化插件
前端·javascript·uni-app
zhangyao94033011 小时前
uniapp动态修改 顶部导航栏标题和右侧按钮权限显示隐藏
前端·javascript·uni-app
2501_9160074714 小时前
iOS 压力测试的工程化体系,构建高强度、多维度、跨工具协同的真实负载测试流程
android·ios·小程序·uni-app·cocoa·压力测试·iphone
2501_9160088916 小时前
API接口调试全攻略 Fiddler抓包工具、HTTPS配置与代理设置实战指南
前端·ios·小程序·https·fiddler·uni-app·webview
2501_9159214317 小时前
iOS 开发者工具推荐,构建从调试到性能优化的多维度生产力工具链(2025 深度工程向)
android·ios·性能优化·小程序·uni-app·iphone·webview
00后程序员张19 小时前
全面解析网络抓包工具使用:Wireshark和TCPDUMP教程
网络·ios·小程序·uni-app·wireshark·iphone·tcpdump
游戏开发爱好者820 小时前
Mac 抓包软件怎么选?从 HTTPS 调试、TCP 数据流分析到多工具协同的完整抓包方案
tcp/ip·macos·ios·小程序·https·uni-app·iphone
2501_915918411 天前
苹果上架 iOS 应用的工程实践,一次从零到上线的完整记录
android·ios·小程序·https·uni-app·iphone·webview