h5+的Downloader下載網絡圖片緩存到本地的案例

以前展現圖片都是經過<img src="網絡圖片地址"> , 每次都請求服務器, 加載比較慢;
如何作到顯示圖片的時候先從本地獲取,沒有則聯網下載,緩存到本地;下次直接從本地拿,無需再聯網;javascript

用Android機測試是成功的,蘋果機尚未試:html

<!DOCTYPE html> <html>  <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> </head>  <body> <div class="mui-content"> <img id="img1"/> <img id="img2"/> <img id="img3"/> </div> </body>  <script src="../js/mui.js" type="text/javascript" charset="utf-8"></script>  <script type="text/javascript" charset="utf-8"> mui.init(); //mui初始化 mui.plusReady(function() { setImg("img1", "http://ask.dcloud.net.cn/uploads/avatar/000/00/00/16_avatar_max.jpg"); setImg("img2", "http://client.bbzuche.com/resources/product/2014012094648828751145/20150611/logo.jpg"); setImg("img3", "http://www.bbzuche.com/images/tan.jpg"); });  /*<img>設置圖片 *1.從本地獲取,若是本地存在,則直接設置圖片 *2.若是本地不存在則聯網下載,緩存到本地,再設置圖片 * */ function setImg(imgId, loadUrl) { if (imgId == null || loadUrl == null) return; //圖片下載成功 默認保存在本地相對路徑的"_downloads"文件夾裏面, 如"_downloads/logo.jpg" var filename = loadUrl.substring(loadUrl.lastIndexOf("/") + 1, loadUrl.length); var relativePath = "_downloads/" + filename; //檢查圖片是否已存在 plus.io.resolveLocalFileSystemURL(relativePath, function(entry) { console.log("圖片存在,直接設置=" + relativePath); //若是文件存在,則直接設置本地圖片 setImgFromLocal(imgId, relativePath); }, function(e) { console.log("圖片不存在,聯網下載=" + relativePath); //若是文件不存在,聯網下載圖片 setImgFromNet (imgId,loadUrl,relativePath); }); }  /*給圖片標籤<img>設置本地圖片 * imgId 圖片標籤<img>的id * relativePath 本地相對路徑 例如:"_downloads/logo.jpg" */ function setImgFromLocal(imgId, relativePath) { //本地相對路徑("_downloads/logo.jpg")轉成SD卡絕對路徑("/storage/emulated/0/Android/data/io.dcloud.HBuilder/.HBuilder/downloads/logo.jpg"); var sd_path = plus.io.convertLocalFileSystemURL(relativePath); //給<img>設置圖片 $id(imgId).setAttribute("src", sd_path); }  /*聯網下載圖片,並設置給<img>*/ function setImgFromNet (imgId,loadUrl,relativePath) { //先設置下載中的默認圖片 $id(imgId).setAttribute("src", "../images/loading.png"); //建立下載任務 var dtask = plus.downloader.createDownload(loadUrl, {}, function(d, status) { if (status == 200) { //下載成功 console.log("下載成功=" + relativePath); setImgFromLocal(imgId, d.filename); } else { //下載失敗,需刪除本地臨時文件,不然下次進來時會檢查到圖片已存在 console.log("下載失敗=" + status+"=="+relativePath); //dtask.abort();//文檔描述:取消下載,刪除臨時文件;(但經測試臨時文件沒有刪除,故使用delFile()方法刪除); if (relativePath!=null) delFile(relativePath); } }); //啓動下載任務 dtask.start(); }  /*刪除指定文件*/ function delFile(relativePath) { plus.io.resolveLocalFileSystemURL(relativePath, function(entry) { entry.remove(function(entry) { console.log("文件刪除成功==" + relativePath); }, function(e){ console.log("文件刪除失敗="+ relativePath);});});}/*根據id查找元素*/function $id(id){return document.getElementById(id);}</script></html>
相關文章
相關標籤/搜索