h5+的Downloader下载网络图片缓存到本地的案例

之前展示图片都是通过<img src="/static/css/default/img/default.jpg" data-original="网络图片地址"> , 每次都请求服务器, 加载比较慢;
如何做到显示图片的时候先从本地获取,没有则联网下载,缓存到本地;下次直接从本地拿,无需再联网;

我用Android机测试是成功的,苹果机还没有试,有问题欢迎指出:

<!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="/static/css/default/img/default.jpg" data-original="../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>
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要在uniapp中下载文件并保存到本地,你可以使用两种方法。 方法一:使用uni.downloadFile和uni.saveFile函数。 首先,使用uni.downloadFile函数下载文件,该函数接受一个对象参数,包含文件的下载URL。下载成功后,使用uni.saveFile函数将文件保存到本地,该函数也接受一个对象参数,其中的tempFilePath属性指定要保存的文件的临时路径。保存成功后,可以使用uni.openDocument函数打开文件。请注意,保存的文件位置可能比较奇怪,比如在安卓端可能是"内部存储\Android\data\io.dcloud.HBuilder\apps\HBuilder\doc\uniapp_save"。此外,还要注意保存过程中文件名可能会被篡改。因此,建议使用方法二。 方法二:使用plus.downloader.createDownload和plus.io.convertLocalFileSystemURL函数。 首先,使用plus.downloader.createDownload函数创建一个下载任务,该函数接受两个参数,文件的下载地址和文件保存的路径。下载成功后,使用plus.io.convertLocalFileSystemURL函数将保存在本地的相对路径转换为平台绝对路径。然后,使用plus.runtime.openFile函数选择一个软件打开文件。最后,显示一个toast提示文件已保存。如果下载失败,可以使用plus.downloader.clear函数清除下载任务。请注意,安卓端文件管理内的路径是file://storage/emulated/0/xx。 下面是一个例子用来下载文件并保存到本地: uni.downloadFile({ url: 文件的下载路径, success(res) { uni.saveFile({ tempFilePath: res.tempFilePath, success: function(res) { const savedFilePath = res.savedFilePath; uni.openDocument({ filePath: savedFilePath, success: function(res) { uni.hideLoading() }, fail: function(res) {}, complete: function(res) { setTimeout(uni.hideLoading(), 4000) }, }); }, fail: function(err) {} }); }, fail(res) {} }) 请注意替换代码中的"文件的下载路径"为实际文件的下载URL。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [uniapp 下载文件和保存到本地](https://blog.csdn.net/shelter123456/article/details/126038481)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [【下载文件】uniapp开发小程序,下载文件并保存到本地](https://blog.csdn.net/weixin_48596030/article/details/126015687)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值