微信小程序下载文件到本地

问题描述

文件下载不了也打开失败,微信里说有10m但是没有10m的文件也下载不了,为什么呢?

原因

之前下载了一些内容已经超过10m,需要清理 微信小程序下载文件到本地_第1张图片

解决方案

微信文档中描述的是本地文件存储的大小限制为 10M, 所以在下载之前可以先清空之前存储的垃圾数据

下载文件到本地的具体过程

使用 wx.downloadFile 先下载文件,再使用 wx.saveFile 将下载的临时文件保存到本地,再使用 wx.openDocument 打开保存后的文件。

wx.getSavedFileList({  // 获取文件列表
  success(res) {
    res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
      // 删除存储的垃圾数据
      wx.removeSavedFile({
        filePath: val.filePath
      });
    })
  }
})
wx.downloadFile({
      url: 下载文件的地址,
      success: function (res) {
        const tempFilePath = res.tempFilePath;
        // 保存文件
        wx.saveFile({
          tempFilePath,
          success: function (res) {
            const savedFilePath = res.savedFilePath;
            // 打开文件
            wx.openDocument({
              filePath: savedFilePath,
              success: function (res) {
                console.log('打开文档成功')
              },
            });
          },
          fail: function (err) {
            console.log('保存失败:', err)
          }
        });
      },
      fail: function (err) {
        console.log('下载失败:', err);
      },
    });

转载于:https://my.oschina.net/u/3913691/blog/3072325

你可能感兴趣的:(微信小程序下载文件到本地)