jul*_*bou 126 javascript upload file-upload
FileJavaScript中有一个对象.我想实例化一个用于测试目的.
我试过了new File(),但是我收到了"非法构造函数"错误.
是否可以创建一个File对象?
Ala*_*inD 183
根据W3C File API规范,File构造函数需要2(或3)个参数.
所以创建一个空文件做:
var f = new File([""], "filename");
Run Code Online (Sandbox Code Playgroud)
第三个参数看起来像:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
Run Code Online (Sandbox Code Playgroud)它适用于FireFox,Chrome和Opera,但不适用于Safari或IE/Edge.
End*_*ess 27
现在你可以!
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);Run Code Online (Sandbox Code Playgroud)
Nic*_*ski 18
更新
如果您将BlobBuilder 用于测试目的,那么BlobBuilder已被淘汰,看看您如何使用它.
否则应用以下的迁移策略转到Blob,例如这个问题的答案.
作为替代方案,有一个Blob可以代替File使用,因为它是File接口根据W3C规范派生的:
interface File : Blob {
readonly attribute DOMString name;
readonly attribute Date lastModifiedDate;
};
Run Code Online (Sandbox Code Playgroud)
File接口基于Blob,继承blob功能并将其扩展为支持用户系统上的文件.
在现有的JavaScript方法上使用这样的BlobBuilder,它通过文件上传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);
Run Code Online (Sandbox Code Playgroud)
其余的样本以更完整的方式在jsFiddle上运行,但由于我无法长期暴露上传逻辑,因此无法成功上传.
现在所有主要浏览器都可以并支持:https://developer.mozilla.org/en-US/docs/Web/API/File/File
var file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227984 次 |
| 最近记录: |