微信小程序合并文件

简介

项目需求。

核心代码

index.js

1
// 获取应用实例
2
const app = getApp()
3
const fs = wx.getFileSystemManager()
4
5
Page({
6
  data: {
7
    originFilePath: '',
8
    chooseFilePath: ''
9
  },
10
  // 选择源文件文件
11
  chooseOriginFile() {
12
    wx.chooseMessageFile({
13
      count: 1,
14
      type: 'file',
15
      success: res => {
16
        const file = res.tempFiles[0]
17
        const originFilePath = this.saveFile(file.name, file.path)
18
        this.setData({ originFilePath })
19
      }
20
    })
21
  },
22
  // 选择文件
23
  chooseFile() {
24
    wx.chooseMessageFile({
25
      count: 1,
26
      type: 'file',
27
      success: res => {
28
        const file = res.tempFiles[0]
29
        const chooseFilePath = this.saveFile(file.name, file.path)
30
        this.setData({ chooseFilePath })
31
      }
32
    })
33
  },
34
  // 保存文件
35
  saveFile(name, file) {
36
    // wx.env.USER_DATA_PATH: "http://usr"
37
    // fs.appendFile只能操作wx.env.USER_DATA_PATH目录下文件,其他目录没有权限
38
    const writeFilePath = `${wx.env.USER_DATA_PATH}/${name}`
39
    const res = fs.saveFileSync(file, writeFilePath)
40
    console.log(res, 'saveFile')
41
    return res
42
  },
43
  // 合并文件
44
  mergeFile() {
45
    const { originFilePath, chooseFilePath } = this.data
46
    const readChooseFilePath = fs.readFileSync(chooseFilePath)
47
    fs.appendFile({
48
      filePath: originFilePath,
49
      data: readChooseFilePath,
50
      encoding: 'utf8',
51
      success() {
52
        const readOriginFilePath = fs.readFileSync(originFilePath)
53
        console.log(readOriginFilePath)
54
      },
55
      fail(res) {
56
        console.error(res)
57
      }
58
    })
59
  }
60
})

index.wxml

1
<!-- index.wxml -->
2
<view class="container">
3
  <view>
4
    <button type="primary" bindtap="chooseOriginFile">选择源文件</button>
5
    <text wx:if="{{originFilePath}}">{{originFilePath}}</text>
6
  </view>
7
  <view>
8
    <button type="primary" bindtap="chooseFile">
9
      选择往源文件里追加的文件
10
    </button>
11
    <text wx:if="{{chooseFilePath}}">{{chooseFilePath}}</text>
12
  </view>
13
  <view>
14
    <button type="warning" bindtap="mergeFile">合并文件</button>
15
  </view>
16
</view>

index.wxss

1
view {
2
  margin-top: 20rpx;
3
}

参考链接

1.https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.appendFile.html