Create a file object from an img tag

前端 未结 2 1898
心在旅途
心在旅途 2021-02-14 05:28

Let\'s say that I have an img tag with a base64 src like :


How can I create a

2条回答
  •  一整个雨季
    2021-02-14 06:05

    The File Object inherits the Blob object, so it is very close to being the same.

    The code below shows a successfully generated File "Blob" object can be used to generate a object url which downloads the image.

    ( Note: on stack overflow the blob url has a null host which causes it to not to automatically download as a file, but you can still use right click save as. See URL.createObjectURL returns a blob with null prepended. Eg : Blob:null/12415-63 )

    // https://bl.ocks.org/nolanlawson/0eac306e4dac2114c752 
    let dataUrl = document.getElementById("img1").src.split(',')
    let base64 = dataUrl[1];
    let mime = dataUrl[0].match(/:(.*?);/)[1];
    let bin = atob(base64);
    let length = bin.length;
    // From http://stackoverflow.com/questions/14967647/ (continues on next line)
    // encode-decode-image-with-base64-breaks-image (2013-04-21)
    let buf = new ArrayBuffer(length);
    let arr = new Uint8Array(buf);
    bin
      .split('')
      .forEach((e,i)=>arr[i]=e.charCodeAt(0));
      
    let f = new File([buf],'filename',{type:mime}); // note: [buf]
    let blobUrl = URL.createObjectURL(f);
    let link = document.createElement("a"); 
    link.href = blobUrl;
    link.download = "filename";
    link.innerHTML = "Download file.";
    document.getElementById("url1").appendChild(link);
    
    

提交回复
热议问题