首頁  >  文章  >  web前端  >  uniapp怎麼存圖片到本地

uniapp怎麼存圖片到本地

PHPz
PHPz原創
2023-04-20 15:05:217167瀏覽

隨著行動互聯網和行動應用的發展,使用者在使用應用程式中儲存和管理大量的圖片已經得到廣泛的應用。 Uniapp是一款基於Vue.js開發的跨平台框架,可輕鬆開發出小程式、H5、App等應用程式。在開發過程中,有時需要將獲取的圖片保存到本地,以便下次快速調用,下面我們就來看看Uniapp怎麼保存圖片到本地。

一. 取得圖片
在開發過程中,我們需要使用到圖片,我們可以透過uni.request或uni.dow​​nloadFile來取得圖片資源。

  1. uni.request
    uni.request是Uniapp中進行網路請求的常用方法,我們可以透過設定responseType的屬性來取得圖片資源。具體代碼如下:
uni.request({
  url: 'http://www.example.com/resource/1.jpg',
  responseType: 'arraybuffer',
  success: (res) => {
    uni.saveFile({
      tempFilePath: res.tempFilePath,
      success: (saveRes) => {
        console.log(saveRes);
      }
    });
  }
});

其中,url為圖片的鏈接,responseType為'arraybuffer'表示以二進制形式獲取圖片資源,獲取成功後將其保存到tempFilePath中,最後通過uni.saveFile來將圖片儲存到本地。

  1. uni.dow​​nloadFile
    uni.dow​​nloadFile是Uniapp中進行下載檔案的常用方法,我們可以透過設定url的屬性來取得圖片資源。具體代碼如下:
uni.downloadFile({
  url: 'http://www.example.com/resource/1.jpg',
  success: (res) => {
    uni.saveFile({
      tempFilePath: res.tempFilePath,
      success: (saveRes) => {
        console.log(saveRes);
      }
    });
  }
});

其中,url為圖片的鏈接,獲取成功後將其保存到tempFilePath中,最後通過uni.saveFile將圖片保存到本地。

二. 儲存圖片
我們已經取得了圖片資源,接下來就需要將其儲存到本機。透過uni.saveFile可以將檔案保存在本機,但是每個平台的儲存路徑都不相同,Uniapp封裝了一個方法getFileSystemManager,可以取得到目前平台的本機儲存路徑。

具體程式碼如下:

uni.getFileSystemManager().access({
  path: '/storage/emulated/0/uniapp_demo/',
  success: () => {
    uni.saveFile({
      tempFilePath: res.tempFilePath,
      filePath: '/storage/emulated/0/uniapp_demo/1.jpg',
      success: (res) => {
        console.log('保存成功');
      }
    });
  },
  fail: () => {
    uni.getFileSystemManager().mkdir({
      dirPath: '/storage/emulated/0/uniapp_demo/',
      success: () => {
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          filePath: '/storage/emulated/0/uniapp_demo/1.jpg',
          success: (res) => {
            console.log('保存成功');
          }
        });
      }
    });
  }
});

其中,path為本地儲存路徑,透過access來判斷目錄是否存在,不存在就透過mkdir來建立目錄,最後透過uni.saveFile將檔案儲存到本地。

三. 結語
以上就是Uniapp中如何將圖片儲存到本地的方法,開發者可以依照自己的需求進行調整。在使用過程中遇到問題可以透過Uniapp官網文件或社群中的貼文來解決。希望本文能對您有所幫助。

以上是uniapp怎麼存圖片到本地的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn