小程序读本地文件

场景

  • 大家应该都知道的api wx.getFileSystemManager()提供了readFile方法来读目标文件,但是需要在知道文件路径的前提下才能读到的。那么现在的场景是,用户自己选择文件,然后读取被选择文件的内容,能不能想web端一样,用input file选择本地文件呢?如果不能,该什么实现呢?

实现

  • 首先说明,小程序的<input type=""/>这个标签的type类型只有:text、number、idcard、digit、time和date, 是没有file型的,所以不能通过input标签实现选择本地文件
  • 但是选择图片、视频、音频这类操作在小程序里还是很常见的,既然没有input,那么官方肯定会提供其他api来实现这些需求
    1. 选择图片,用wx.chooseImage
    wx.chooseImage({
      count: 1, // 允许选择的图片数,默认为9
      sizeType: ['original', 'compressed'], // original原图,compressed压缩图,默认二者都有,用户可选择
      sourceType: ['album', 'camera'], // album相册,camera相机,默认二者都有,用户可选择图片来源
      success (res) {
        // path 可以作为image标签的src属性显示图片
        const path = res.tempFilePaths[0]
      }
    })
    
    // 比如在.wxml中有一个image标签
    <image src="{{img}}"></image>
    
    // 那么在js中
    ···
    data: {
      img: ''
    },
    selectImage () {
      const that = this
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          that.setData({
            img: res.tempFilePaths[0]
          })
        }
      })
    },
    ···
    
    // 这样在选择了图片之后,页面标签的位置就会显示被选择的图片
    
    1. 选择视频,用wx.chooseVideo
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60, // 最大视频长度,单位 s
      camera: 'back', // 前后摄像头,默认为back后置摄像头,front为前置摄像头
      success(res) { // res包含该视频的大部分基本信息
        console.log(res.tempFilePath) // 视频在本机的路径
      }
    })
    
    1. 其他,用wx.chooseMedia
    // 其实就是视频和图片二合一
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log(res)
      }
    })
    
  • 那么如果想要的是其他文件怎么办呢?答案是,微信小程序不支持从手机本地直接读其他类型的文件,但是!它支持从聊天会话里读所有类型的文件,所以可以讲需要的文件先发给好友,也可以是微信文件助手,然后就能读到发的文件了。
    wx.chooseMessageFile
    const fs = wx.getFileSystemManager()
    wx.chooseMessageFile({
      count: 1,
      type: 'all', // all, video, image, file 四种,默认为all
      success(res) {
        console.log(res)
        // 同样,读到的只是文件在本机的路径,而要读文件内容,就用一开始提到的wx.getFileSystemManager()的readFile就好了
        fs.readFile({
          filePath: res.tempFiles[0].path,
          encoding: 'utf8',
          position: 0,
          success(file) {
            console.log(file)
          }
        })
      }
    })
    
posted @ 2022-11-01 16:41  Mizuki-Vone  阅读(1410)  评论(0)    收藏  举报