Question

I'm using the following FileReader script to try and upload attachments to an object in 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:

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

Would anyone have any suggestions?

Was it helpful?

Solution

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top