js下载图片


/**
 * @param {*} imgData 图片对象
 * @param {*} str     图片下载到本地的文件名
 * @param {*} type    图片下载到本地的类型
 */
function commonDownloads(blob, name, type) {
    
    
  try {
    
    
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    
    
      // 兼容ie
      window.navigator.msSaveOrOpenBlob(blob, name);
    } else {
    
    
      const downloadElement = document.createElement("a");
      downloadElement.innerHTML = `${
      
      name} download`;
      downloadElement.style["margin"] = "2px 2px";
      downloadElement.style["display"] = "block";
      const href = window.URL.createObjectURL(blob); // 静态方法会创建一个 DOMnameing,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象
      downloadElement.href = href;
      downloadElement.download = name;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href); // 释放之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
    }
  } catch (error) {
    
    
    console.error("download err -> ", error);
  }
}
function imageDownload(blob, index) {
    
    
  const name = `${
      
      index.toString().padStart(3, "0")}.png`;
  const type =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  commonDownloads(blob, name, type);
}

猜你喜欢

转载自blog.csdn.net/printf_hello/article/details/114261223