ale*_*nst 13 javascript fileapi
JavaScript有两个File和Blob的文件表示,无一不是几乎同样的事情.有没有办法检查变量是持有一种数据File还是一种Blob数据?
Nic*_*unt 30
最简单的方法:
a = new File([1,2,3], "file.txt");
b = new Blob([1,2,3]);
c = "something else entirely";
a instanceof File
> true
b instanceof File
> false
c instanceof File
> false
Run Code Online (Sandbox Code Playgroud)
W3.org:
'File对象是一个带有name属性的Blob对象,它是一个字符串;'
如果是文件:
var d = new Date(2013, 12, 5, 16, 23, 45, 600);
var generatedFile = new File(["Rough Draft ...."], "Draft1.txt", {type: 'text/plain', lastModified: d});
console.log(typeof generatedFile.name == 'string'); // true
Run Code Online (Sandbox Code Playgroud)
如果是Blob:
var blob = new Blob();
console.log(typeof blob.name); // undefined
Run Code Online (Sandbox Code Playgroud)
条件:
var isFile = typeof FileOrBlob.name == 'string';
Run Code Online (Sandbox Code Playgroud)
一种使生活更轻松的衬垫解决方案。
基于 Ric Flair
const isFile = input => 'File' in window && input instanceof File;
const isBlob = input => 'Blob' in window && input instanceof Blob;
const a = new File([1,2,3], "foo.txt", {type: "text/plain"});
...
console.log(isFile(a)) // true
...
Run Code Online (Sandbox Code Playgroud)
小智 7
基于尼克·布伦特的:
function isFile(input) {
if ('File' in window && input instanceof File)
return true;
else return false;
}
function isBlob(input) {
if ('Blob' in window && input instanceof Blob)
return true;
else return false;
}
//Test
const a = new File([1,2,3], "foo.txt", {type: "text/plain"});
const b = new Blob([1,2,3]);
const c = "something else entirely";
console.log(isFile(a)); //true
console.log(isBlob(a)); //true
console.log(isFile(b)); //false
console.log(isBlob(b)); //true
console.log(isFile(c)); //false
console.log(isBlob(c)); //false
Run Code Online (Sandbox Code Playgroud)
不适用于 Opera mini 和 IE。尽管在 IE 中这并不重要,因为您可能只使用文件输入标签,在这种情况下您肯定会知道它是一个文件。
| 归档时间: |
|
| 查看次数: |
17652 次 |
| 最近记录: |