目录

微信小程序合并文件

微信小程序合并文件

微信小程序合并文件

简介

项目需求。

核心代码

index.js

// 获取应用实例
const app = getApp()
const fs = wx.getFileSystemManager()

Page({
  data: {
    originFilePath: '',
    chooseFilePath: ''
  },
  // 选择源文件文件
  chooseOriginFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: res => {
        const file = res.tempFiles[0]
        const originFilePath = this.saveFile(file.name, file.path)
        this.setData({ originFilePath })
      }
    })
  },
  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: res => {
        const file = res.tempFiles[0]
        const chooseFilePath = this.saveFile(file.name, file.path)
        this.setData({ chooseFilePath })
      }
    })
  },
  // 保存文件
  saveFile(name, file) {
    // wx.env.USER_DATA_PATH: "http://usr"
    // fs.appendFile只能操作wx.env.USER_DATA_PATH目录下文件,其他目录没有权限
    const writeFilePath = `${wx.env.USER_DATA_PATH}/${name}`
    const res = fs.saveFileSync(file, writeFilePath)
    console.log(res, 'saveFile')
    return res
  },
  // 合并文件
  mergeFile() {
    const { originFilePath, chooseFilePath } = this.data
    const readChooseFilePath = fs.readFileSync(chooseFilePath)
    fs.appendFile({
      filePath: originFilePath,
      data: readChooseFilePath,
      encoding: 'utf8',
      success() {
        const readOriginFilePath = fs.readFileSync(originFilePath)
        console.log(readOriginFilePath)
      },
      fail(res) {
        console.error(res)
      }
    })
  }
})

index.wxml

<!-- index.wxml -->
<view class="container">
  <view>
    <button type="primary" bindtap="chooseOriginFile">选择源文件</button>
    <text wx:if="{{originFilePath}}">{{originFilePath}}</text>
  </view>
  <view>
    <button type="primary" bindtap="chooseFile">
      选择往源文件里追加的文件
    </button>
    <text wx:if="{{chooseFilePath}}">{{chooseFilePath}}</text>
  </view>
  <view>
    <button type="warning" bindtap="mergeFile">合并文件</button>
  </view>
</view>

index.wxss

view {
  margin-top: 20rpx;
}

参考链接