要在JavaScript中下载图片链接,可以使用以下方法之一:

  1. 使用浏览器的内置下载功能:可以创建一个隐藏的<a>标签,将图片链接设置为href属性,然后使用click()方法模拟点击该链接,触发下载操作。
function downloadImage(url) {
  var link = document.createElement('a');
  link.href = url;
  link.download = 'image.png';
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
  1. 使用XMLHttpRequest(XHR)对象进行文件下载:创建一个XHR对象,将图片链接设置为请求的URL,然后使用responseType属性将响应类型设置为blob,最后使用createObjectURL方法创建一个临时URL,可以使用<a>标签模拟下载。
function downloadImage(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  
  xhr.onload = function() {
    if (xhr.status === 200) {
      var blob = xhr.response;
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = 'image.png';
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };
  
  xhr.send();
}

请注意,由于浏览器的安全策略限制,如果要下载的图片链接不在同一个域名下,可能会遇到跨域问题。在这种情况下,可以使用服务器端代理来下载图片。

js 打开图片链接会打开新页面怎么下载

原文地址: https://www.cveoy.top/t/topic/i4Hh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录