如何在 JavaScript 中实例化 File 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8390855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to instantiate a File object in JavaScript?
提问by julesbou
There's a File
object in JavaScript. I want to instantiate one for testing purposes.
File
JavaScript 中有一个对象。我想实例化一个用于测试目的。
I have tried new File()
, but I get an "Illegal constructor" error.
我试过了new File()
,但我收到“非法构造函数”错误。
Is it possible to create a File
object ?
是否可以创建File
对象?
File Object reference : https://developer.mozilla.org/en/DOM/File
回答by AlainD
According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.
根据 W3C File API 规范,File 构造函数需要 2(或 3)个参数。
So to create a empty file do:
因此,要创建一个空文件,请执行以下操作:
var f = new File([""], "filename");
- The first argument is the data provided as an array of lines of text;
- The second argument is the filename ;
The third argument looks like:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
- 第一个参数是作为文本行数组提供的数据;
- 第二个参数是文件名;
第三个参数看起来像:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.
它适用于 FireFox、Chrome 和 Opera,但不适用于 Safari 或 IE/Edge。
回答by Endless
Now you can!
现在你可以!
var parts = [
new Blob(['you construct a file...'], {type: 'text/plain'}),
' Same way as you do with blob',
new Uint16Array([33])
];
// Construct a file
var file = new File(parts, 'sample.txt', {
lastModified: new Date(0), // optional - default = now
type: "overide/mimetype" // optional - default = ''
});
var fr = new FileReader();
fr.onload = function(evt){
document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate
}
fr.readAsText(file);
回答by Nick Josevski
Update
BlobBuilder has been obsoletedsee how you go using it, if you're using it for testing purposes.
Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.
更新
BlobBuilder 已过时,如果您将其用于测试目的,请查看您如何使用它。
否则,将以下内容与转到Blob 的迁移策略一起应用,例如此问题的答案。
Use a Blob instead
改用 Blob
As an alternative there is a Blobthat you can use in place of Fileas it is what File interface derives from as per W3C spec:
作为替代方案,您可以使用Blob代替File,因为它是根据W3C 规范派生的 File 接口:
interface File : Blob {
readonly attribute DOMString name;
readonly attribute Date lastModifiedDate;
};
The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
File 接口基于 Blob,继承 Blob 功能并对其进行扩展以支持用户系统上的文件。
Create the Blob
创建 Blob
Using the BlobBuilderlike this on an existing JavaScript method that takes a File to upload via XMLHttpRequest
and supplying a Blob to it works fine like this:
像这样在现有的 JavaScript 方法上使用BlobBuilder,该方法需要通过 File 上传XMLHttpRequest
并为其提供 Blob,这样可以正常工作:
var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);
xhr.responseType = 'arraybuffer';
bb.append(this.response); // Note: not xhr.responseText
//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');
/* more setup code */
xhr.send(blob);
Extended example
扩展示例
The rest of the sample is up on jsFiddlein a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.
示例的其余部分以更完整的方式出现在jsFiddle 上,但无法成功上传,因为我无法以长期方式公开上传逻辑。
回答by Pavel Evstigneev
Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File
现在所有主要浏览器都可以并支持:https: //developer.mozilla.org/en-US/docs/Web/API/File/File
var file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
回答by SNS - Web et Informatique
The idea ...To create a File object (api) in javaScript for images already present in the DOM :
这个想法......在javaScript中为DOM中已经存在的图像创建一个文件对象(api):
<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">
var file = new File(['fijRKjhudDjiokDhg1524164151'],
'../img/Products/fijRKjhudDjiokDhg1524164151.jpg',
{type:'image/jpg'});
// created object file
console.log(file);
Don't do that ! ... (but I did it anyway)
不要那样做!......(但我还是做到了)
-> the console give a result similar as an Object File :
-> 控制台给出类似于对象文件的结果:
File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d'été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d'été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File
But the size of the object is wrong ...
但是对象的大小是错误的......
Why i need to do that ?
为什么我需要这样做?
For example to retransmit an image form already uploaded, during a product update, along with additional images added during the update
例如,在产品更新期间重新传输已上传的图像表单以及更新期间添加的其他图像
回答by Ian1971
Because this is javascript and dynamic you could define your own class that matches the File interface and use that instead.
因为这是 javascript 和动态的,所以您可以定义自己的与 File 接口匹配的类并使用它。
I had to do just that with dropzone.js because I wanted to simulate a file upload and it works on File objects.
我不得不用 dropzone.js 做到这一点,因为我想模拟文件上传并且它适用于 File 对象。