小程序 文件创建、追加、删除、上传云服务

2023-03-31  本文已影响0人  hao_developer
image.png
const fs = wx.getSystemFileManager();
可以获取到全局唯一的文件系统管理器,所有文件系统的管理操作通过 FileSystemManager 来调用
1:创建文件前fs.writeFile,必须要先创建目录fs.mkdir和检查是否存在fs.access
2:在当前文件中追加数据fs.appendFile
3:删除当前目录中所有文件 读取目录中所有文件fs.readdir--->循环files.forEach--->删除fs.unlink
wx.env.USER_DATA_PATH
本地文件的文件路径均为以下格式:{{协议名}}://文件路径
其中,协议名在 iOS/Android 客户端为 "wxfile",在开发者工具上为 "http",开发者无需关注这个差异,也不应在代码中去硬编码完整文件路径。
注意:filePath一定要和你存储的路径一模一样才可以删除成功!不然会报没有删除权限errMsg:"unlink:fail fail permission denied, open "http://usr/data1800330233101.doc""(这个小程序的报错提示也是真的坑.)
http://usr/data1800330233101.doc
需要改成
http://usr/data/1800330233101.doc

wxml

<button bindtap="clickHandler" data-operation="{{1}}" type="default" style="margin-top: 10rpx;">创建目录</button>
<button bindtap="clickHandler" data-operation="{{2}}" type="default" style="margin-top: 10rpx;">写入文件</button>
<button bindtap="clickHandler" data-operation="{{3}}" type="default" style="margin-top: 10rpx;">文件是否存在</button>
<button bindtap="clickHandler" data-operation="{{4}}" type="default" style="margin-top: 10rpx;">保存文件</button>
<button bindtap="clickHandler" data-operation="{{5}}" type="default" style="margin-top: 10rpx;">打开文件</button>
<button bindtap="clickHandler" data-operation="{{6}}" type="default" style="margin-top: 10rpx;">继续写入</button>
<button bindtap="clickHandler" data-operation="{{7}}" type="default" style="margin-top: 10rpx;">删除文件</button>
<button bindtap="clickHandler" data-operation="{{8}}" type="default" style="margin-top: 10rpx;">上传文件</button>

js

let fs = null;

Page({
  data: {
    filePath: '', //文件地址
    tempDatas: [
      [
        10, 11, 12, 13, 14, 15, 16, 17, '123456789'
      ]
    ]
  },
  onLoad(options) {
    fs = wx.getFileSystemManager();
  },
  onShow() {},
  clickHandler(e) {
    const operation = e.currentTarget.dataset.operation;
    switch (operation) {
      case 1: //创建目录
        const _filePath = `${wx.env.USER_DATA_PATH}/data`;
        fs.mkdir({
          dirPath: _filePath,
          recursive: false,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          },
        });
        break;
      case 2: //写入文件
        const filePath_ = `${wx.env.USER_DATA_PATH}/data/` + Date.now() + '.doc';
        this.data.filePath = filePath_;
        fs.writeFile({
          filePath: filePath_,
          data: '1234567890',
          encoding: 'utf8',
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          },
        });
        break;
      case 3: //文件是否存在
        fs.access({
          path: this.data.filePath,
          success(res) {
            console.log(res);
          },
          fail(err) {
            console.log(err);
          }
        })
        break;
      case 4: //保存文件
        fs.saveFile({
          tempFilePath: this.data.filePath,
          success: (result) => {
            console.log(result);
          },
          fail: (res) => {
            console.log(res);
          },
        })
        break;
      case 5: //打开文件
        wx.openDocument({
          filePath: this.data.filePath,
          fileType: 'doc',
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        })
        break;
      case 6: //继续写入
        fs.appendFile({
          filePath: this.data.filePath,
          data: '\n' + this.data.tempDatas + '',
          encoding: 'utf8',
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          },
        });
        break;
      case 7: //删除 `${wx.env.USER_DATA_PATH}/data/`文件夹下所有文件
        console.log(this.data.filePath);
        fs.readdir({
          dirPath: wx.env.USER_DATA_PATH,
          success: (res) => {
            console.log('readdir', res);
            res.files.forEach((el) => {
              fs.unlink({
                filePath: `${wx.env.USER_DATA_PATH}/${el}`.replace(/data/g, "data/"),
                success: (res) => {
                  console.log('unlink',res);
                },
                fail: (err) => {
                  console.log('unlink', err);
                }
              })
            })
          },
          fail: (err) => {
            console.log('readdir',err);
          }
        })
        break;
      case 8: //上传文件(云服务接口)
        wx.showLoading({
          title: '请稍后',
        });
        const _that = this;
        const name = this.data.filePath.substr(this.data.filePath.lastIndexOf('/') + 1)
        wx.cloud.uploadFile({
          cloudPath: 'data/' + name, // 指定上传到的云路径
          filePath: _that.data.filePath,
        }).then(res => {
          console.log('上传成功-云存储', res);
          wx.hideLoading();
          wx.showToast({
            title: '上传成功',
          })
        }).catch(err => {
          console.log('上传失败', err);
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
          })
        });
        break;
    }
  }
})
上一篇 下一篇

猜你喜欢

热点阅读