Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I'm trying to store a long JSON string as a Document. The problem is that when I download this doc and open it I see unreadable text with signs and strange characters. looks like I opened a binary file. This is my JS function on the VF page,where body is my string; what am I doing wrong?

function createDocument(body){
    //            console.log("body: " + body);
    var document = new sforce.SObject('Document');
    var now = new Date();
    document.Name = now + '_DataStore.json';
    document.Body = body;
    document.FolderId = '005d0000000fLdI';
    document.ContentType = 'application/json';
    result = sforce.connection.create([document]);

    if(!result[0].getBoolean("success")){
        alert("Failed to create document");
    }
    else{
        window.location.href='/'+result[0].id;
    }
}
share|improve this question

1 Answer 1

up vote 3 down vote accepted

Per the documentation on the Document object, you need to base64 encode the data stored in the body field.

Body - Type: base64, Description: Encoded file data.

Encoded Data

The API sends and receives the binary file data encoded as a base64 data type. Prior to creating a record, clients must encode the binary file data as base64. Upon receiving an API response, clients must decode the base64 data to binary (this conversion is usually handled for you by the SOAP client).

There are quite a few ways to do this. If this code is executing in a newer browser you can use the btoa() method available on the window object. If your browsers do not support the btoa() method , you'll probably need to find a library which you like that can handle this encoding instead.

function createDocument(body) {
    // console.log("body: " + body);
    var document = new sforce.SObject('Document');
    var now = new Date();
    document.Name = now + '_DataStore.json';

    // base64 encode the body string
    document.Body = window.btoa(body);

    document.FolderId = '005d0000000fLdI';
    document.ContentType = 'application/json';
    result = sforce.connection.create([document]);
    if (!result[0].getBoolean("success")) {
        alert("Failed to create document");
    } else {
        window.location.href = '/' + result[0].id;
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.