uniapp 圖片緩存


方案1:

在獲取數據后調用

this.getLocalPath(this.list, this.fixPath)

1.先遍歷數據,看看本地有沒有圖片的靜態文件

 1 getLocalPath(list, callback) {
 2                 plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => {
 3                     fs.root.createReader().readEntries((entries) => {
 4                         let data = [];
 5                         for (var i = 0; i < entries.length; i++) {
 6                             data.push(entries[i].fullPath)
 7                         }
 8                         callback(data, list)
 9                     })
10                 })
11             }

2.1.有數據則替換為本地路徑

2.2 沒有數據則返回個錯誤鏈接

fixPath(data, list) {
                list.forEach(item => {
                    let arr = item.img.split('/')
                    let filename = arr[arr.length - 1]
                    let filePath = data.find(path => path.includes(filename)) 
                    item.img = filePath ? 'file://' + filePath : filename
                })
            }

3.當圖片錯誤的時候執行@error事件,事件內先拼接正確的鏈接隨后下載圖片

<image :src="item.img" mode="heightFix" @error="imageError(item)"></image>

 

imageError(item) {
                let httpUrl = 'https://xxx/'  // 服務器地址
                let url = httpUrl + item.img
                this.$set(item, 'img', url)
                // 下載到本地
                plus.downloader.createDownload(url, {}, (d, status) => {
                    status != 200 && console.log('error')
                    console.log("Download success: " + d.filename);
                }).start()
            }

 

 

方案2:

不使用@error,性能不如方案1

其他代碼一樣,2.2如下

fixPath(data, list) {
                list.forEach(item => {
                    if (item.type == 'image' || item.type == 'forwardimage') {
                        let arr = item.payload.url.split('/')
                        let filename = arr[arr.length - 1]
                        let filePath = data.find(path => path.includes(filename))
                        // 如果在本地找到了,則讀取本地路徑,沒有則下載到本地
                        if (filePath) {
                            item.payload.url = 'file://' + filePath
                        } else {
                            plus.downloader.createDownload(item.payload.url, {}, (d, status) => {
                                status != 200 && console.log('error')
                                console.log("Download success: " + d.filename);
                            }).start()
                        }
                    }
                })
            }

 

h5+參考API  https://www.html5plus.org/doc/zh_cn/io.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM