javascript Chrome 中的 FileReader 错误 - JS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23150902/
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
Error with FileReader in Chrome - JS
提问by Daft
I'm using the following FileReader script to try and upload attachments to an object in Salesforce.
我正在使用以下 FileReader 脚本尝试将附件上传到 Salesforce 中的对象。
<label>Select file: <input id="file-input" type="file" name="file" onChange="uploadFile()"></input>
function uploadFile()
{
var f = document.getElementById('file-input').file;
var reader = new FileReader();
// Keep a reference to the File in the FileReader so it can be accessed in callbacks
reader.file = f;
reader.onerror = function(e)
{
switch(e.target.error.code)
{
case e.target.error.NOT_FOUND_ERR:
alert('File Not Found!');
break;
case e.target.error.NOT_READABLE_ERR:
alert('File is not readable');
break;
case e.target.error.ABORT_ERR:
break; // noop
default:
alert('An error occurred reading this file.');
};
};
reader.onabort = function(e)
{
alert('File read cancelled');
};
reader.onload = function(e)
{
var att = new sforce.SObject("Attachment");
att.Name = this.file.name;
att.ContentType = this.file.type;
att.ParentId = parentId;
att.Body = (new sforce.Base64Binary(e.target.result)).toString();
sforce.connection.create([att],
{
onSuccess : function(result, source)
{
if (result[0].getBoolean("success"))
{
console.log("new attachment created with id " + result[0].id);
}
else
{
console.log("failed to create attachment " + result[0]);
}
},
onFailure : function(error, source)
{
console.log("An error has occurred " + error);
}
});
};
reader.readAsBinaryString(f);
}
But I'm getting the following error message: in Chrome:
但我收到以下错误消息:在 Chrome 中:
Uncaught TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': The argument is not a Blob.
Would anyone have any suggestions?
有人会有什么建议吗?
回答by Ray Nicholus
The file object(s)on the file input in modern browsers are part of an array.
现代浏览器中文件输入的文件对象是数组的一部分。
You must change this line:
您必须更改此行:
var f = document.getElementById('file-input').file;
to:
到:
var f = document.getElementById('file-input').files[0];