JS实现下载图片并且重命名

2020-04-152488次阅读javascript

本例共有AJAX、Fetch两种实现方法代码片段,仅供参考,Ajax与Fetch API的区别请参考这里

 

Ajax实现下载图片并且重命名

getBase64=(val)=>{
        const _this=this
        window.URL = window.URL || window.webkitURL;
        const xhr = new XMLHttpRequest();
        xhr.open("get", val, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status == 200) {
            const blob = this.response;
            _this.createImg(blob,val)
          }
        }
        xhr.send();
      }
 
 
    createImg=(params,url)=> {
        const name=url.match(/com\/(\S*)\?/)[1]
        const fileName = `${name}.jpg`
        const elink =document.createElement('a');
        elink.download=fileName
        elink.style.display='none'
        elink.href = URL.createObjectURL(params);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
    }

 

Fetch API实现下载图片并且重命名

<a  @click.prevent="downLoadImg(item.url,item.name)" crossOrigin="anonymous" style="margin-top:6px;" class="addBtn fixed" target="_blank" :href="item.url">下载</a>
methods: {

    async downLoadImg(url,fileName){

        window.URL = window.URL || window.webkitURL;


        try {

            const blob = await downImgUrl(`${url}?time=${new Date().valueOf()}`);

            this.createImg(blob,fileName);

            
        } catch(e) {
            return console.log(e);
        }




    },

    createImg(params,fileName){

        const elink =document.createElement('a');
        elink.download=fileName
        elink.style.display='none'
        elink.href = URL.createObjectURL(params);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
    }
    ....
}

上方是Vue实战实现下载图片并且重命名,整个过程注意事项如下:

1、下载图片遇到跨域的问题,需要后端或运维配合设置Response Headers里的Access-Control-Allow-Origin字段跟随。

add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';

前端相应配合是给下载资源添加crossOrigin="anonymous"属性。

2、按上方配置jpg格式没有问题,但遇到gif格式还是跨域???黑科技给下载资源添加后缀?time=new Date().valueOf()解决了。

3、async/ await结合Promise使用,如何接住Promise抛出的错误

参考:

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/blob

https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

https://developer.mozilla.org/zh-CN/docs/Web/API/File/Using_files_from_web_applications#Example.3A_Using_object_URLs_to_display_images

上一篇: 移动端IOS横竖屏切换横屏时字体变大  下一篇: 将HTML字符串转换为DOM对象  

JS实现下载图片并且重命名相关文章