JS 实现跨域外链下载图片(不支持IE)

跨域需要服务器设置

function ddd(){
            // ES6 语法
            let src = 'https://fenmul.github.io/Sin.gtihub.io/images/qrcode.bmp';
            var canvas = document.createElement('canvas');
            var img = document.createElement('img');
            img.onload = function(e) {
                canvas.width = img.width;
                canvas.height = img.height;
                var context = canvas.getContext('2d');
                context.drawImage(img, 0, 0, img.width, img.height);
                canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
                canvas.toBlob((blob)=>{
                    let link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = '1';
                link.click();
            }, "");
            }
            img.setAttribute("crossOrigin",'Anonymous');
            img.src = src;
        }

基于 ES6 语法实现,不支持 ie 浏览器

https://www.jianshu.com/p/6fe06667b748

js 图片和 base64 互相转换
https://www.cnblogs.com/zhuchenglin/p/7528723.html

Java 将图片转化为 Base64

/**
     * 将网络图片编码为base64
     */
    public static String encodeImageToBase64(URL url) throws Exception {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        System.out.println("图片的路径为:" + url.toString());
//打开链接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
            conn.setRequestMethod("GET");
//超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
            byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
//使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
//关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
//对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encode(data);
            System.out.println("网络文件[{}]编码成base64字符串:[{}]"+base64);
            return base64;//返回Base64编码过的字节数组字符串
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片获取失败,请联系客服!");
        }
    }

页面再进行解码

$(function () {
//        var userList = [11,22,33,44];
//
//        $.each(userList,function(i,item){

//            console.log(i, item);
            $.ajax({
                type: "post",
                url: "${etlUrl}/etlYs/d",
                async:false,
                success: function (data) {
                    var blob = convertBase64UrlToBlob(data);
                    console.log(blob);
                    if (myBrowser() == 'IE') {
                        window.navigator.msSaveBlob(blob, '1.jpg');
                    } else {
                        var _a = document.createElement('a');
                        _a.download = '1.jpg';
                        _a.href = URL.createObjectURL(blob);
                        _a.click();
                    }
                },
                error: function (data) {
                    tipInfo("操作失败!");
                }
            });
//        });

    });
    /**
     * 将 base64 转换位 blob 对象
     * blob 存储 2进制对象的容器
     * @export
     * @param {*} base64
     * @returns
     */
    function convertBase64UrlToBlob(base64) {
        var parts = base64.split(';base64,');
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;
        var uInt8Array = new Uint8Array(rawLength);
        for (var i = 0; i < rawLength; i++) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
    }

    // 判断浏览器类型
    function myBrowser() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        if (userAgent.indexOf("OPR") > -1) {
            return "Opera";
        }; //判断是否Opera浏览器 OPR/43.0.2442.991
        if (userAgent.indexOf("Firefox") > -1) {
            return "FF";
        } //判断是否Firefox浏览器  Firefox/51.0
        if (userAgent.indexOf("Trident") > -1) {
            return "IE";
        } //判断是否IE浏览器  Trident/7.0; rv:11.0
        if (userAgent.indexOf("Edge") > -1) {
            return "Edge";
        } //判断是否Edge浏览器  Edge/14.14393
        if (userAgent.indexOf("Chrome") > -1) {
            return "Chrome";
        } // Chrome/56.0.2924.87
        if (userAgent.indexOf("Safari") > -1) {
            return "Safari";
        } //判断是否Safari浏览器 AppleWebKit/534.57.2 Version/5.1.7 Safari/534.57.2
    }

服务器允许跨域时可以直接使用js实现

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function down(url, name) {
            var image = new Image();
            image.crossOrigin = "Anonymous";
            image.src = url;
            image.onload = function () {
                var base64 = getBase64Image(image);
                document.getElementById('img').setAttribute( 'src', base64);
                var blob = convertBase64UrlToBlob(base64);
                if (myBrowser() == 'IE') {
                    window.navigator.msSaveBlob(blob, name + '.jpg');
                } else {
                    var _a = document.createElement('a');
                    _a.download = name;
                    _a.href = URL.createObjectURL(blob);
                    _a.click();
                }
            }
        }

        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
            var dataURL = canvas.toDataURL("image/"+ext);
            return dataURL;
        }

        function convertUrlToBase64(url) {
            return new Promise(function (resolve, reject) {
                var img = new Image();
                img.crossOrigin = 'Anonymous';
                img.src = url;
                img.onload = function () {
                    var canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
                    var dataURL = canvas.toDataURL('image/' + ext);
                    var base64 = {
                        dataURL: dataURL,
                        type: 'image/' + ext,
                        ext: ext
                    };
                    resolve(base64);
                };
            });
        }

        /**
         * 将 base64 转换位 blob 对象
         * blob 存储 2进制对象的容器
         * @export
         * @param {*} base64
         * @returns
         */
        function convertBase64UrlToBlob(base64) {
            var parts = base64.split(';base64,');
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
            var uInt8Array = new Uint8Array(rawLength);
            for (var i = 0; i < rawLength; i++) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], { type: contentType });
        }

        // 判断浏览器类型
        function myBrowser() {
            var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
            if (userAgent.indexOf("OPR") > -1) {
                return "Opera";
            }; //判断是否Opera浏览器 OPR/43.0.2442.991
            if (userAgent.indexOf("Firefox") > -1) {
                return "FF";
            } //判断是否Firefox浏览器  Firefox/51.0
            if (userAgent.indexOf("Trident") > -1) {
                return "IE";
            } //判断是否IE浏览器  Trident/7.0; rv:11.0
            if (userAgent.indexOf("Edge") > -1) {
                return "Edge";
            } //判断是否Edge浏览器  Edge/14.14393
            if (userAgent.indexOf("Chrome") > -1) {
                return "Chrome";
            } // Chrome/56.0.2924.87
            if (userAgent.indexOf("Safari") > -1) {
                return "Safari";
            } //判断是否Safari浏览器 AppleWebKit/534.57.2 Version/5.1.7 Safari/534.57.2
        }

    </script>
</head>
<body>
<button onclick="down('https://cdn.pingwest.com/portal/2019/01/17/W3KF2YMYW1b2j13bcYNs4c006feXP53S.jpeg?x-oss-process=style/pw_pc_article',1)">1</button>
<img id="img" src=""/>
</body>
</html>

图片下载到本地

/**
 * @Author: lixin
 * @Date: 2019/1/16
 * @Description: savePath 需要加上文件名
 */
public void downloadImg(String imgUrl, String savePath) {
    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // 发送get请求
    HttpGet httpGet = new HttpGet(imgUrl);
    // 设置请求和传输超时时间
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(100000).setConnectTimeout(100000).build();
    //设置请求头
    httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
    httpGet.setConfig(requestConfig);
    try {
        CloseableHttpResponse response = httpclient.execute(httpGet);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            HttpEntity entity = response.getEntity();
            logger.info("下载图片返回的entity对象:"+entity+"对应的Content:"+entity.getContent());
            InputStream in = entity.getContent();
            FileUtils.copyInputStreamToFile(in, new File(savePath));
            logger.info("下载图片成功:"+imgUrl);
        }
    } catch (IOException e) {
        logger.error("downloadImg", e);
    } finally {
        httpGet.releaseConnection();
    }
}

你可能感兴趣的:(Web)