微信小程式檔案預覽和下載-檔案系統

DCodes發表於2023-11-25

檔案預覽和下載

在下載之前,我們得先呼叫介面獲取檔案下載的url
然後透過wx.downloadFile將下載檔案資源到本地

wx.downloadFile({
   url: res.data.url,
   success: function (res) {
      console.log('資料',res);
   }
})

tempFilePath就是臨時臨時檔案路徑。
透過wx.openDocument開啟檔案。
showMenu表示預覽檔案右上方的選單,你可以在該選單中選擇儲存檔案,將檔案顯示的儲存到本地。

// 預覽和下載
wx.downloadFile({
   url: res.data.url,
   success: function (res) {
      const filePath = res.tempFilePath  // 臨時檔案路徑
      wx.openDocument({
         filePath: filePath,
         showMenu: true // 預覽檔案右上方的...
      })
    }
})

到這裡檔案的預覽和儲存就完成了,你可以顯示的看到檔案的儲存位置。
這是檔案操作的其中一種方式,如果你要具體的操作檔案,請繼續向下看。


檔案系統

檔案系統是這篇著重要講的,其實在上文中提到的wx.downloadFile這一步就是檔案下載的關鍵,檔案下載成功(臨時)會觸發success回撥,你可以透過DownloadTask監聽檔案下載的進度,當downloadTask進度為100時,downloadFilesuccess下載成功就會被觸發。

      const downloadTask = wx.downloadFile({
        url: res.data.url,
        success: function (res) {
          // progress進度100時觸發success
        }
      })
      downloadTask.onProgressUpdate((res) => {
        console.log('下載進度', res.progress)
        console.log('已經下載的資料長度', res.totalBytesWritten)
        console.log('預期需要下載的資料總長度', res.totalBytesExpectedToWrite)
      })

wx.downloadFiletempFilePath對應的就是臨時檔案的儲存位置,這個檔案是會被刪除的。因此如果你需要持久化檔案,則需要呼叫saveFile來儲存檔案。同時tempFilePath也可以作為一箇中轉,為後續使用資源提供支援,所以我們在後續呼叫wx.openDocument時,tempFilePath其實是做了檔案中轉,在openDocument對檔案做了後續的儲存或預覽操作。

微信小程式本身自帶一個檔案系統,官網介紹:檔案系統

在檔案系統中有關於本地臨時檔案的介紹:

本地臨時檔案只能透過呼叫特定介面產生,不能直接寫入內容。本地臨時檔案產生後,僅在當前生命週期內保證有效,重啟之後不一定可用。如果需要保證在下次啟動時無需下載,可透過 FileSystemManager.saveFile()FileSystemManager.copyFile() 介面把本地臨時檔案轉換成本地快取檔案或本地使用者檔案。

在上文中我們將wx.downloadFile返回的臨時路徑當作中轉,呼叫wx.openDocument來儲存檔案,這是一種方法,還有一種就是操作檔案系統API,對臨時檔案進行移動、儲存、複製等操作。

下面我們透過檔案系統來實現檔案的儲存:

API檔案:wx.getFileSystemManager()

流程如下:

1、獲取檔案下載url

2、wx.downloadFile下載檔案

3、判斷資料夾是否存在:

  • 存在:透過saveFile直接下載
  • 不存在:透過mkdir建立資料夾,建立完成後,透過saveFile直接下載
  async downloadPdf(id) {
    let that = this;
    let res = await getPdfAPI(id);
    // 下載檔案
    wx.downloadFile({
      url: res.data.url,
      success: async (res) => {
        // 設定儲存路徑
        let myPath = wx.env.USER_DATA_PATH + '/MyFile'
        try {
          // 判斷資料夾是否存在
          await that.fileExist(myPath)
          // 存在: 儲存檔案到本地
          await that.fileSave(res.tempFilePath, myPath).catch(err => console.log(err));
          wx.showToast({
            title: '儲存成功',
            icon: 'none'
          })
        } catch (e) {
          // 不存在: 建立資料夾
          await that.fileMkdir(myPath).catch(err => console.log(err));
          // 儲存檔案到本地
          await that.fileSave(res.tempFilePath, myPath).catch(err => console.log(err));
          wx.showToast({
            title: '儲存成功',
            icon: 'none'
          })
        }
      }
    })
  },

  // 儲存檔案
  fileSave(tempFilePath, myPath) {
    return new Promise(function (resolve, reject) {
      const fileManager = wx.getFileSystemManager(); // 檔案系統
      fileManager.saveFile({
        tempFilePath: tempFilePath, // 臨時檔案路徑
        filePath: myPath + '/myFileName.pdf',  // 資料夾路徑 + 檔名
        success: function (res) {
          resolve(res)
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  },

  // 建立資料夾
  fileMkdir(myPath) {
    return new Promise(function (resolve, reject) {
      const fileManager = wx.getFileSystemManager(); // 檔案系統
      fileManager.mkdir({
        dirPath: myPath, // 資料夾路徑
        success: function (mkdir) {
          resolve(mkdir)
        },
        fail: function (mkdirerr) {
          reject(mkdirerr)
        }
      })
    })
  },

  // 判斷資料夾是否存在
  fileExist(myPath) {
    return new Promise(function (resolve, reject) {
      const fileManager = wx.getFileSystemManager(); // 檔案系統
      fileManager.access({
        path: myPath,  // 資料夾路徑
        success: function (exist) {
          resolve(exist)
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  },

注意點:

1、saveFile自定義儲存路徑filePath資料夾路徑+檔名的拼接

2、saveFile接收的檔案路徑為wx.downloadFile獲取的臨時路徑tempFilePath

3、wx.env.USER_DATA_PATH是一個字串,表示檔案系統中的使用者目錄路徑 (本地路徑)

關於儲存位置:

PC端中:

wx.env.USER_DATA_PATH預設指向usr資料夾,微信開發者工具中可以看到儲存路徑:

真機中:
真機的預設儲存位置為:內部儲存/Android/data/com.tencent.mm/MicroMsg/wxanewfiles/
也就是wxanewfiles資料夾下的子資料夾,該資料夾不固定


參考檔案:
wx.downloadFile
wx.openDocument
DownloadTask
wx.env
檔案系統
wx.getFileSystemManager()
FileSystemManager.mkdir(Object object)
FileSystemManager.saveFile(Object object)
FileSystemManager.access(Object object)


如果你覺得本文章不錯,歡迎點贊?、收藏?、轉發✨哦~
閱讀其它:
微信小程式記住密碼,讓登入解放雙手 (?點選直達)
微信小程式動態生成表單來啦!你再也不需要手寫表單了! (?點選直達)
根據URL批次下載檔案並壓縮成zip檔案 (?點選直達)
檔案、影片、圖片上傳(點選、拖拽、批次匯入)要‍‍‍‍怎麼實現?! (?點選直達)
一文搞懂原型和原型鏈 (?點選直達)

相關文章