在大哥王(andy)神一样的带领下,我们牛逼闪闪的走上了使用h5plus技术实现跨平台技术开发的道路,一路高歌!!!
下面我要分享的内容是如何实现图片本地缓存。
废话不说,直接看代码:
/**
* 声明获取图片的方法
* @param {Object} picUrl 图片的网络地址
* @param {Object} defaultPic 默认图片
* @param {Object} element 图片源元素
*/
function fetchImage(picUrl, defaultPic, element) {
//将图片网络地址进行md5摘要。
var filename = hex_md5(picUrl);
element.setAttribute("src", defaultPic);
//尝试加载本地图片
plus.io.resolveLocalFileSystemURL("_downloads/" + filename, function(entry) {
// 加载本地图片成功
entry.file( function(file){
if(file.size==0){
//console.log("2.1图片为空显示默认");
element.setAttribute("src", defaultPic);
}else{
var path = plus.io.convertLocalFileSystemURL("_downloads/" + filename);
//console.log("2.1加载本地图片"+path);
element.setAttribute("src", path);
}
});
}, function(e) {
//加载本地图片失败,本地没有该图片,尝试从网络下载图片并保存本地,保存文件名为url摘要md5值
var dtask = plus.downloader.createDownload(picUrl, {filename:filename}, function(d, status) {
// 下载完成
if (status == 200) {
if(d.downloadedSize==0){
//console.log("2.2图片为空显示默认");
element.setAttribute("src", defaultPic);
}else{
//console.log("2.2下载网络文件成功"+d.url);
element.setAttribute("src", d.url);
}
}
});
dtask.start();
});
}
以上主要用到h5plus的两个重要的api
1.Downloader模块管理网络文件下载任务,用于从服务器下载各种文件,并支持跨域访问操作。
2.IO模块管理本地文件系统,用于对文件系统的目录浏览、文件的读取、文件的写入等操作。通过plus.io可获取文件系统管理对象。
详见官方:
刚开始做的时候准备使用html5的indexedDB存储图片来的,但是后来发现在移动设备上不好用。参考https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/