微信小程序学习之路——API文件

文件

从网络下载、拍照、录音、录视频时,文件都是存在临时文件中,需要永久保存这些文件就需要我们主动调用API进行保存,这时小程序会将文件保存到系统指定目录,关于这些文件操作都需要调用相关API

wx.saveFile(Object)

保存文件到本地,本地文件存储大小限制为10MB,Object参数属性如下:

属性 类型 默认值 必填 说明
tempFilePath string   需要保存的文件的临时路径
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.startRecord({//开始录音
  success:function(res){
    var tempFilePath = res.tempFilePath//临时文件路径
    wx.saveFile({//保存临时文件
      tempFilePath: 'tempFilePath',
      success:function(res){
        var savedFilePath = res.savedFilePath;//永久地址路径
        console.log('录音文件已保存到:'+savedFilePath);
      }
    })
  }
})

wx.getSavedFileList(Object)

获取本地已保存文件列表,Object参数属性如下:

属性 类型 默认值 必填 说明
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.getSavedFileList({
  success:function(res){
    for(var i =0,file;file =res.fileList[i];++i){
      console.log('第'+i+'个文件路径:'+file.filePath);
    }
  }
});

wx.getSavedFileInfo(Object)

获取本地文件的文件信息,Object属性如下:

属性 类型 默认值 必填 说明
filePath string   文件路径
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.getSavedFileList({
  success:function(res){
    for(var i =0,file;file=res.fileList[i];++i){
      wx.getSavedFileInfo({
        filePath: 'file,filePath',
        success:function(res){
          console.log('文件大小为:'+res.size);
        }
      });
    }
  }
});

wx.removeSavedFile(Object)

删除本地存储文件,Object参数属性如下:

属性 类型 默认值 必填 说明
filePath string   需要删除的文件路径
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.getSavedFileList({
  success:function(res){
    //删除所有文件
    for(var i=0,file;file=res.fileList[i];++i){
      wx.removeSavedFile({
        filePath: 'file.filePath',
      });
    }
  }
});

wx.openDocument(Object)

在新页面中打开文档,支持格式有:doc、docx、xls、xlsx、ppt、pptx、pdf,Object参数属性如下:

属性 类型 默认值 必填 说明 最低版本
filePath string   文件路径,可通过 downloadFile 获得  
fileType string   文件类型,指定文件类型打开文件 1.4.0
success function   接口调用成功的回调函数  
fail function   接口调用失败的回调函数  
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码如下:

wx.downloadFile({
  url:'hppt://www.myserver.com/my.docx',
  success:function(res){
    var filePath  =res.filePath;
    //下载文档后在新页面中预览
    wx.openDocument({
      filePath: 'filePath',
    });
  }
});

猜你喜欢

转载自blog.csdn.net/CSDN_XUWENHAO/article/details/89032274