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
}
相关推荐
RuoyiOffice2 小时前
2026 企业定制开发选型:从零开发、低代码、SaaS 与 RuoYi Office 怎么选?
spring boot·uni-app·开源·saas·oa·定制化·ruoyioffice
三天不学习16 小时前
【超详细】Vue3+UniApp+.NET8集成腾讯云IM即时通信全攻略
uni-app·.net·腾讯云·im·即时通信
于先生吖16 小时前
前后端分离人事招聘项目,校招宣讲预约+社招双向撮合功能架构设计教程
java·开发语言·uni-app
QQ_51100828516 小时前
uniapp微信小程序网上饰品商城售卖系统php python物流
微信小程序·uni-app·php
2501_9159090620 小时前
深入解析Mock.js:功能、应用及实战案例,提升前端开发效率
android·ios·小程序·https·uni-app·iphone·webview
于先生吖21 小时前
前后端分离体育服务项目,场馆计费+线下赛事排行小程序部署开发教程
java·小程序·uni-app
蜡台21 小时前
Uniapp 实现预览pdf 文件
pdf·uni-app·pdfh5
不想吃饭e1 天前
uniapp-图片,视频上传组件封装
java·uni-app·音视频
2501_916007471 天前
不用 Mac 也可以 Windows下管理iOS描述文件的非Xcode完整指南
android·ios·小程序·https·uni-app·iphone·webview
于先生吖2 天前
UniApp搭配Java后端实现到店预约上门指派,订单状态流转与结算开发教程
java·开发语言·uni-app