likes
comments
collection
share

vue项目通过a标签下载图片至zip包

作者站长头像
站长
· 阅读数 13

在vue项目中,将图片下载可使用流的形式,下载成单个图片,或者将多个图片下载至zip包,以下就是介绍使用a标签下载图片的用法:

1、图片下载

// url为网络图片地址
axios
.get(url, {
  responseType: "blob",
  withCredentials: false,
})
.then((e) => {
  const href = URL.createObjectURL(e.data);
  const aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.href = href;
  aLink.download = "图片测试.png";
  aLink.click();
  URL.revokeObjectURL(url);
});

2、图片下载成zip压缩包

axios
.get(url, {
  responseType: "blob",
  withCredentials: false,
}).then((e) => {
  const blob = new Blob([e], { type: "application/zip" });
  const url = URL.createObjectURL(blob);
  const aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.href = url;
  aLink.setAttribute("download", new Date() + ".zip");
  document.body.append(aLink);
  aLink.click();
  document.body.removeChild(aLink);
  URL.revokeObjectURL(url);
});