Chrome中的FileReader出错 - JS

时间:2014-04-18 09:05:23

标签: javascript salesforce blob filereader

我正在使用以下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);
        }

但是我收到以下错误消息:在Chrome中:

Uncaught TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': The argument is not a Blob.

有人会有任何建议吗?

1 个答案:

答案 0 :(得分:2)

现代浏览器中文件输入上的文件对象是数组的一部分。

您必须更改此行:

var f = document.getElementById('file-input').file;

到:

var f = document.getElementById('file-input').files[0];