单张图片下载

  1. handleAlipayQrCode(id,name){
  2. // 请求后端接口返回url
  3. addAlipayQrCode(id).then(response=>{
  4. this.downloadByBlob(response.data.url,name);
  5. });
  6. },
  7. downloadByBlob(url,name) {
  8. let image = new Image()
  9. image.setAttribute('crossOrigin', 'anonymous')
  10. image.src = url
  11. image.onload = () => {
  12. let canvas = document.createElement('canvas')
  13. canvas.width = image.width
  14. canvas.height = image.height
  15. let ctx = canvas.getContext('2d')
  16. ctx.drawImage(image, 0, 0, image.width, image.height)
  17. canvas.toBlob((blob) => {
  18. let url = URL.createObjectURL(blob)
  19. this.download(url,name)
  20. // 用完释放URL对象
  21. URL.revokeObjectURL(url)
  22. })
  23. }
  24. },
  25. download(href, name) {
  26. let eleLink = document.createElement('a')
  27. eleLink.download = name
  28. eleLink.href = href
  29. eleLink.click()
  30. eleLink.remove()
  31. },

图片打包下载

  1. 打开命令行,执行以下命令

    1. npm i jszip
    2. npm i file-saver
  2. 在对应的页面加上以下代码

    1. import FileSaver from 'file-saver';
    2. import JSZip from 'jszip';
    3. let imgList =[
    4. {
    5. name: '图片一',
    6. baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
    7. },
    8. {
    9. name: '图片二',
    10. baseImg: 'https://res.miaocode.com/web/mk/csys/bg3_new.png',
    11. },
    12. ]

批量导出方法

  1. exportImg() {
  2. this.getImageZip('科室二维码', this.imgList);
  3. },
  4. getImageZip(title, imgList, eachImgKey = 'name', eachUrlKey = 'baseImg') {
  5. let zip = new JSZip();
  6. let imgs = zip.folder(title);
  7. let baseList = [];
  8. imgList.forEach(imgD => {
  9. let name = imgD[eachImgKey]; //每张图片的名称
  10. let image = new Image();
  11. // 解决跨域 Canvas 污染问题
  12. image.setAttribute('crossOrigin', 'anonymous');
  13. image.onload = function() {
  14. let canvas = document.createElement('canvas');
  15. canvas.width = image.width;
  16. canvas.height = image.height;
  17. let context = canvas.getContext('2d');
  18. context.drawImage(image, 0, 0, image.width, image.height);
  19. let url = canvas.toDataURL(); // 得到图片的base64编码数据
  20. canvas.toDataURL('image/png');
  21. baseList.push({ name, img: url.substring(22) });
  22. if (baseList.length === imgList.length) {
  23. if (baseList.length > 0) {
  24. baseList.forEach(baseImg => {
  25. imgs.file(baseImg.name + '.png', baseImg.img, {
  26. base64: true
  27. });
  28. });
  29. zip.generateAsync({ type: 'blob' }).then(content => {
  30. FileSaver.saveAs(content, title + '.zip');
  31. });
  32. }
  33. }
  34. };
  35. image.src = imgD[eachUrlKey] = `${imgD[eachUrlKey]}`;
  36. });
  37. },