uniapp 读,写,删本地文件

<template>
    <view>
        <view class="p-2">
            <view class="bg-primary p-2 rounded flex align-center justify-center" style="color: #fff;"  hover-class="bg-hover-primary" @click="dataset">写入{{count}} s</view>
        </view>
        <view class="p-2">
            <view class="bg-primary p-2 rounded flex align-center justify-center" style="color: #fff;" hover-class="bg-hover-primary" @click="read">读取</view>
        </view>
       
        <view class="p-2">
            <view class="bg-primary p-2 rounded flex align-center justify-center" style="color: #fff;" hover-class="bg-hover-primary" @click="deletes">删除</view>
        </view>
    </view>
</template>

<script>
    import { mapState } from 'vuex'
    export default {
        data() {
            return {
                count: '',
                timer: null,
                resultdata:[]
            }
        },
        computed: {
            ...mapState({
                token:state=>{
                    return state.user ? state.user.token : null
                },
                user:state=>{
                    return state.user ? state.user : null
                }
            }),
       
        },
   
        methods: {
       
            read(){
                //console.log("读取")
                plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, (fs)=> {
                              // fs.root是根目录操作对象DirectoryEntry
                              let a = fs.root.toURL()  //通过此方法我们可获取存储在app私用环境下的相对跟路径。
                            console.log(a + '/box/' + 'test.json')
                              fs.root.getFile(a + '/box/' + 'test.json', {
                                  create: false
                              }, (fileEntry)=> {
                                  // 文件在手机中的路径
                                 // console.log(fileEntry.fullPath)
                                  fileEntry.file((file)=> {
                                      var fileReader = new plus.io.FileReader();
                                     fileReader.readAsText(file, 'utf-8');
                                     fileReader.onloadend =(evt)=> {
                                         var news = [];
                                         var result = evt.target.result;
                                        console.log(result)
                                         if (result != ""){
                                             this.resultdata=JSON.parse(result)
                                           
                                         }
                                             
                                     }
                                 });
                             });
                         })
               
            },
            wetir(){
                //console.log("写入")
                plus.io.requestFileSystem(
                              plus.io.PUBLIC_DOCUMENTS, // 文件系统中的根目录
                              fs => {
                                   let a = fs.root.toURL()  //通过此方法我们可获取存储在app私用环境下的相对跟路径。
                                  // 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
                                  fs.root.getFile(a + '/box/' + 'test.json', {
                                      create: true // 文件不存在则创建
                                  }, fileEntry => {
                                      // 文件在手机中的路径
                                  //  console.log(fileEntry.fullPath)
                                     fileEntry.createWriter(writer => {
                                         // 写入文件成功完成的回调函数
                                         writer.onwrite = e => {
                                             console.log("写入数据成功");                    
                                        };
                                        //console.log(this.resultdata)
                                         // 写入数据
                                         writer.write(JSON.stringify(this.resultdata));
                                         uni.hideLoading()
                                     })
                               }, e => {
                                     console.log("getFile failed: " + e.message);
                                 });
                             },
                             e => {
                                 console.log(e.message);
                             }
                        );
            },
            deletes(){
                //console.log("删除文件")
               
                        plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, (fs)=> {
                            // fs.root是根目录操作对象DirectoryEntry
                            let a = fs.root.toURL();
                            //删除目录不能指向文件名  只能指向文件夹
                            console.log(a+'/box/')
                            plus.io.resolveLocalFileSystemURL(a+'/box/' ,(entry)=> {
                                //读取这个目录对象
                                var directoryReader = entry.createReader();
                                //读取这个目录下的所有文件
                                directoryReader.readEntries((entries)=> {
                                    console.log(entries.length)
                                    //如果有才操作
                                    console.log(entries, 'entries')
                                    if (entries.length > 0) {
                                        //删除目录将会删除其下的所有文件及子目录 不能删除根目录,如果操作删除根目录
                                        //将会删除目录下的文件及子目录,不会删除根目录自身。 删除目录成功通过succesCB
                                        //回调返回,失败则通过errorCB返回。
                                        entry.removeRecursively((entry)=> {
                                         
                                            console.log('删除成功回调')
                                            //删除成功回调
                                            this.resultdata=[]
                                           
                                           
                                        }, (e) =>{
                                            //错误信息
                                            console.log(e.message + ' ?!')
                                        })
                                    }
                                })
                            })
               
                })
               
               
            },
            getCode(){
            const TIME_COUNT = 10; //限定时间
            if (!this.timer) {
                this.count = TIME_COUNT;
               
                    this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--; //全局的数据改变 倒计时
                    } else {
                       
                        clearInterval(this.timer);
                        this.timer = null; //清除定时器
                        //需要执行的代码
                        return this.$H.get(`/url`,{
                            token:true
                        }).then(res=>{
                            this.resultdata=res
                            console.log(res)
                            this.wetir()
                           
                        }).catch(err=>{
                            uni.hideLoading()
                        })
                    }
                    }, 1000)
                }
            } ,
            dataset(){
                //避免用户重复点击
                this.getCode()
                uni.showLoading({
                    title: '同步中...'
                });
               
            },
        }
    }
</script>
 

  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在uniapp中下载文件并保存到本地,你可以使用两种方法。 方法一:使用uni.downloadFile和uni.saveFile函数。 首先,使用uni.downloadFile函数下载文件,该函数接受一个对象参数,包含文件的下载URL。下载成功后,使用uni.saveFile函数将文件保存到本地,该函数也接受一个对象参数,其中的tempFilePath属性指定要保存的文件的临时路径。保存成功后,可以使用uni.openDocument函数打开文件。请注意,保存的文件位置可能比较奇怪,比如在安卓端可能是"内部存储\Android\data\io.dcloud.HBuilder\apps\HBuilder\doc\uniapp_save"。此外,还要注意保存过程中文件名可能会被篡改。因此,建议使用方法二。 方法二:使用plus.downloader.createDownload和plus.io.convertLocalFileSystemURL函数。 首先,使用plus.downloader.createDownload函数创建一个下载任务,该函数接受两个参数,文件的下载地址和文件保存的路径。下载成功后,使用plus.io.convertLocalFileSystemURL函数将保存在本地的相对路径转换为平台绝对路径。然后,使用plus.runtime.openFile函数选择一个软件打开文件。最后,显示一个toast提示文件已保存。如果下载失败,可以使用plus.downloader.clear函数清除下载任务。请注意,安卓端文件管理内的路径是file://storage/emulated/0/xx。 下面是一个例子用来下载文件并保存到本地: uni.downloadFile({ url: 文件的下载路径, success(res) { uni.saveFile({ tempFilePath: res.tempFilePath, success: function(res) { const savedFilePath = res.savedFilePath; uni.openDocument({ filePath: savedFilePath, success: function(res) { uni.hideLoading() }, fail: function(res) {}, complete: function(res) { setTimeout(uni.hideLoading(), 4000) }, }); }, fail: function(err) {} }); }, fail(res) {} }) 请注意替换代码中的"文件的下载路径"为实际文件的下载URL。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [uniapp 下载文件和保存到本地](https://blog.csdn.net/shelter123456/article/details/126038481)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [【下载文件uniapp开发小程序,下载文件并保存到本地](https://blog.csdn.net/weixin_48596030/article/details/126015687)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值