云服务器 199 / 年,新老同享,开发者力荐特惠渠道
阿里云推广

图片下载如何能够自定义下载图片的文件名称?前端方案实现

  • 内容
  • 评论
  • 相关




            
            // 点击放大图片
            function showimg(t) {
                var src = $(t).attr("src");
                var title = $(t).attr("title");
                if (src === '') {
                    layer.msg("图片为空!");
                    return false;
                }
                layer.open({
                    type: 1,
                    title: false,
                    content: '<img style="display: inline-block; max-width: 100%; max-height: 100%;" src="' + src + '" title="' + title + '" alt="' + title + '">' +
                        '<a  class="layui-btn layui-btn-sm" href="' + src + '" download="' + title + '">下载图片</a>'
                });
            }



            // 点击放大图片
            function showimg1(t) {
                var src = $(t).attr("src");
                var title = $(t).attr("title");
                if (src === '') {
                    layer.msg("图片为空!");
                    return false;
                }
                layer.open({
                    type: 1,
                    title: false,
                    content: '<img style="display: inline-block; max-width: 100%; max-height: 100%;" src="' + src + '" title="' + title + '" alt="' + title + '">' +
                        '<button  class="layui-btn layui-btn-sm" onclick="downloadImage(\'' + src + '\',\'' + title + '\')">下载图片</button>&nbsp;&nbsp;' +
                        '<a  class="layui-btn layui-btn-sm" href="' + src + '" download="' + title + '">备用下载</a>'
                });
            }

            // 从图片URL创建 Blob 对象
            function createBlobFromImageUrl(imageUrl) {
                return fetch(imageUrl)
                    .then(response => response.blob())
                    .catch(error => console.error('Error fetching image:', error));
            }

            // 等待 Blob 创建完成
            async function downloadImage(imageUrl, imageName) {
                if (imageName === undefined) {
                    imageName = "暂无";
                }
                try {
                    const blob = await createBlobFromImageUrl(imageUrl);
                    const blobUrl = URL.createObjectURL(blob);

                    // 创建一个隐藏的 <a> 标签用于下载
                    const link = document.createElement('a');
                    link.href = blobUrl;
                    link.download = imageName + '.jpg'; // 自定义文件名
                    link.style.display = 'none';
                    document.body.appendChild(link);

                    // 触发点击事件进行下载
                    link.click();

                    // 清理临时资源
                    document.body.removeChild(link);
                    URL.revokeObjectURL(blobUrl);
                } catch (error) {
                    console.error('Error creating blob or downloading image:', error);
                }
            }


            //同步方法废弃了
            function downloadImage_old(imageUrl, imageName) {
                if (imageName === undefined) {
                    imageName = "暂无";
                }
                // 使用 Blob URL 创建一个临时链接
                const imageObj = new Image();
                imageObj.onload = function () {
                    // 将图片转换为 Blob 对象
                    const blob = createBlobFromImageUrl(imageUrl);
                    const blobUrl = URL.createObjectURL(blob);

                    // 创建一个隐藏的 <a> 标签用于下载
                    const link = document.createElement('a');
                    link.href = blobUrl;
                    link.download = imageName + '.jpg'; // 自定义文件名
                    link.style.display = 'none';
                    document.body.appendChild(link);

                    // 触发点击事件进行下载
                    link.click();

                    // 清理临时资源
                    document.body.removeChild(link);
                    URL.revokeObjectURL(blobUrl);
                };
                imageObj.src = imageUrl;
            }



上面一共是2中方案,

方案1:

a标签,src是图片的链接地址,然后download属性是文件名,这种方案简单,但是不同的浏览器处理策略不同,不见得100%如此,还有就是和图片链接有关系

/admin.php/plat/create_erweima_url.html?url=http%3A%2F%2Fhua.lizengtong.com%2F%23%2Fdetail1%3Fgoods_id%3D216663  这种没问题

http://tp5-order.oss-cn-beijing.aliyuncs.com/static/upload/LZTPT/images/202406/B70C594B07EF661711A37BFE842A0E7C.jpg  这种下载文件名仍然是B70C594B07EF661711A37BFE842A0E7C.jpg 

优点:如果图片是非当前域名的图片的话,这种方案没有跨域的问题。

方案2:

根据图片的url创建blob对象,然后创建隐藏的a标签,设置href和download属性,然后模拟点击下载,缺点代码需要客户端支持js,一般都是支持的所以这个可以忽略,其次就是的代码相对复杂一些,不过可以通过封装函数实现调用简单。

缺点:如果图片是非当前域名的图片的话,这种方案有跨域的问题。需要图片服务器去掉跨域,如果那边无法去掉,这种方案就是硬伤!

本文标签:

版权声明:若无特殊注明,本文皆为《菜鸟站长》原创,转载请保留文章出处。

本文链接:图片下载如何能够自定义下载图片的文件名称?前端方案实现 - http://wziyi.net/?post=443

发表评论

电子邮件地址不会被公开。 必填项已用*标注