Create a file object from an img tag

前端 未结 2 1897
心在旅途
心在旅途 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 05:51

    You could always create a blob first and then convert that to a file.

    But you hardly ever need a File instance. It will give you more headache trying to construct them then just using the blob. If you need to upload them to a server you need to use FormData. And when you do you can append a blob and set the filename as a 3th argument
    fd.append(field, blob, filename) instead of appending a file

    The file constructor arguments are the same as blob except between the parts and the options you pass in the filename.

    File Object inherits the Blob object so you use them the same way in other apis as well

    new File([parts], filename, options)
    new Blob([parts], options)
    

    Other thing is that different is file supports 1 more option... lastModified
    IE/Edge can have Files but the constructor don't work. that's why you should use blobs...

    const img = document.getElementById('id')
    
    fetch(img.src)
    .then(res => res.blob())
    .then(blob => {
      const file = new File([blob], 'dot.png', blob)
      console.log(file)
    })
    <img id="id" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">

    0 讨论(0)
  • 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);
    <img id="img1" src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAB1klEQVR42n2TzytEURTHv3e8N1joRhZGzJsoCjsLhcw0jClKWbHwY2GnLGUlIfIP2IjyY2djZTHSMJNQSilFNkz24z0/Ms2MrnvfvMu8mcfZvPvuPfdzz/mecwgKLNYKb0cFEgXbRvwV2s2HuWazCbzKA5LvNecDXayBjv9NL7tEpSNgbYzQ5kZmAlSXgsGGXmS+MjhKxDHgC+quyaPKQtoPYMQPOh5U9H6tBxF+Icy/aolqAqLP5wjWd5r/Ip3YXVILrF4ZRYAxDhCOJ/yCwiMI+/xgjOEzmzIhAio04GeGayIXjQ0wGoAuQ5cmIjh8jNo0GF78QwNhpyvV1O9tdxSSR6PLl51FnIK3uQ4JJQME4sCxCIRxQbMwPNSjqaobsfskm9l4Ky6jvCzWEnDKU1ayQPe5BbN64vYJ2vwO7CIeLIi3ciYAoby0M4oNYBrXgdgAbC/MhGCRhyhCZwrcEz1Ib3KKO7f+2I4iFvoVmIxHigGiZHhPIb0bL1bQApFS9U/AC0ulSXrrhMotka/lQy0Ic08FDeIiAmDvA2HX01W05TopS2j2/H4T6FBVbj4YgV5+AecyLk+CtvmsQWK8WZZ+Hdf7QGu7fobMuZHyq1DoJLvUqQrfM966EU/qYGwAAAAASUVORK5CYII=">
    <div id="url1"></div>

    0 讨论(0)
提交回复
热议问题