Create a file object from an img tag

前端 未结 2 1896
心在旅途
心在旅途 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)
    })

提交回复
热议问题