乐趣区

关于javascript:JS-通过-url-下载图片

如果你从 api 获取了一个图片的 url,应用 <img> 标签能够轻易的将其展现在页面上,然而你并不需要展现它,而是要下载它,怎么办?

上面给出三种解决办法:

应用 fetch:

export const downloadImage = (imageUrl: string, name: string): void => {
  fetch(imageUrl, {
    method: 'get',
    mode: 'cors',
  })
    .then((response) => response.blob())
    .then((data) => {const downloadUrl = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', name);
      document.body.appendChild(link);
      link.click();
      link.remove();});
};

应用 axios:

export const downloadImage = (imageUrl: string, name: string): void => {axios.get(imageUrl, {responseType: 'blob'}).then((res) => {const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', name);
    document.body.appendChild(link);
    link.click();
    link.remove();});
};

应用 canvas:

export const downloadImage = (imageUrl: string, name: string): void => {const image = new Image();
  image.setAttribute('crossOrigin', 'anonymous');
  image.onload = function (): void {console.log(image);
    const canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    const context = canvas.getContext('2d') as CanvasRenderingContext2D;
    context.drawImage(image, 0, 0, image.width, image.height);
    const url = canvas.toDataURL('image/png');
    const a = document.createElement('a');
    const event = new MouseEvent('click');
    a.download = name;
    a.href = url;
    a.dispatchEvent(event);
  };
  image.src = imageUrl;
};
退出移动版