html js 点击下载按钮 下载在线图片

##点击按钮调用方法
// 下载

  downLoadConfirm(url,name) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");

    var filename = '';
    if(reg.test(name)){
      filename  =pinyinUtil.getFirstLetter(name);
    }else {
      filename = name;
    }
    console.log(filename);

    var domImg = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=988369012,233932232&fm=26&gp=0.jpg';
    var domImg = 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3764617837,1933060640&fm=200&gp=0.jpg';
    // var  domImg = 'https://wx4.sinaimg.cn/large/e9b3bee7gy1g1vcyh2mvjj20j60in757.jpg';
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';

    var image = new Image();
    image.src = domImg + '?v=' + Math.random(); // 处理缓存
    image.crossOrigin = "*";  // 支持跨域图片
    var that = this;
    image.onload = function () {
      var base64 = that.getBase64Image(image);
      eleLink.href = base64;
      // 触发点击
      document.body.appendChild(eleLink);
      eleLink.click();
      // 然后移除
      document.body.removeChild(eleLink);
    }
  }


  // 图片转换成base64
  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 dataURL = canvas.toDataURL("image/jpg", 0);  // 可选其他值 image/jpeg
    return dataURL;
  }

angualr 实现方法

  • 采用

var domImg =
‘https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf’;
var x = new XMLHttpRequest();
x.open(“GET”, domImg, true);
x.responseType = “blob”;
x.onload = function (e: ProgressEvent) {
var dd: any = e.target;
// console.log(dd);
var ff = dd.response;
// console.log(ff);
download(ff, “awes.pdf”, “application/pdf”);
};
x.send();

引入:
import downloadjs from ‘downloadjs’ 如果是自己写的函数 没用默认导出 记得加花括号 例如 import { download } from ‘./data.js’

参考:https://baijiahao.baidu.com/s?id=1612392982674092834&wfr=spider&for=pc (格式文件头)
https://github.com/rndme/download

你可能感兴趣的:(在线下载,img,url,angular)