从img标签创建文件对象 [英] Create a file object from an img tag

查看:112
本文介绍了从img标签创建文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有base64 src的img标签,例如:

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

<img src="data:image/jpeg;base64,/9j/4AAQS..." id="id">

如何创建一个File对象(包含img标记的数据),就像用户从文件输入中选择一个文件后得到的对象一样?为了稍后将其上传到服务器.

How can I create a File object (containing the data of the img tag) alike an object I would get after an user chose a file from a file input ? In order to upload it to a server later.

喜欢一个:

File { name: "a22919a70cf8458d654642e0bc2cd881.jpg", lastModified: 1521393615000, lastModifiedDate: Date 2018-03-18T17:20:15.000Z, webkitRelativePath: "", size: 40635, type: "image/jpeg" }

我不是要获取BLOB.

I'm not looking for getting a BLOB.

推荐答案

您总是可以先创建一个Blob,然后将其转换为文件.

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

但是您几乎不需要File实例.尝试仅使用blob来构造它们将使您更加头疼.如果需要将它们上传到服务器,则需要使用FormData.并且当您这样做时,可以附加一个blob并将文件名设置为第三个参数
fd.append(field, blob, filename)而不是附加文件

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

除了在输入文件名的partsoptions之间之外,文件构造函数参数与blob相同.

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

文件对象继承了Blob对象,因此您在其他api中也以相同的方式使用它们

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)

另一件事是,文件支持1个更多选项... lastModified
IE/Edge可以具有文件,但构造函数不起作用.这就是为什么您应该使用斑点的原因...

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==">

这篇关于从img标签创建文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆