Skip to content

Instantly share code, notes, and snippets.

@kevanmoothien
Last active April 17, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevanmoothien/82ff046c59fd0f2bd4a26a09942d969f to your computer and use it in GitHub Desktop.
Save kevanmoothien/82ff046c59fd0f2bd4a26a09942d969f to your computer and use it in GitHub Desktop.
A visualforce page sample to upload content document to a specific record
<apex:page showHeader="false" applyHtmlTag="true" applyBodyTag="false">
    <apex:includeScript value="https://code.jquery.com/jquery-2.2.4.js" />
    <script>
        var PARENT_ID = '0010800002t8mrYAAQ'; //change Id to your record Id
        jQuery(document).ready(function ($) {
            $('input#file').on('change', function (e) {
                for (var i = 0; i < this.files.length; i++) {
                    uploading += 1;
                    upload_file(this.files[i], PARENT_ID, function (err, res) {
                        if (uploading === uploaded) {
                            console.log('uploaded'); //your operation once finish
                        }
                    })
                }
            });
            var uploading = 0;
            var uploaded = 0;
            var upload_file = function (file, parentId, callback) {
                filetoBase64(file, function (err, content) {
                    var body = {
                        compositeRequest: [
                            {
                                method: "POST",
                                url: "/services/data/v51.0/sobjects/ContentVersion",
                                referenceId: "refVersion",
                                body: {
                                    PathOnClient: file.name,
                                    Versiondata: content,
                                    Title: file.name,
                                    Author__c: $('#author').val(),
                                    Email__c: $('#email').val(),
                                    Description: $('#description').val()
                                }
                            },
                            {
                                method: "GET",
                                url: "/services/data/v51.0/sobjects/ContentVersion/@{refVersion.id}/",
                                referenceId: "refVersionGet"
                            },
                            {
                                method: "POST",
                                url: "/services/data/v51.0/sobjects/ContentDocumentLink",
                                referenceId: "refLink",
                                body: {
                                    LinkedEntityId: parentId,
                                    ContentDocumentId: "@{refVersionGet.ContentDocumentId}",
                                    ShareType: "V",
                                    Visibility: "AllUsers"
                                }
                            }
                        ]
                    };

                    $.ajax({
                        url: '/services/data/v51.0/composite',
                        data: JSON.stringify(body),
                        type: 'POST',
                        processData: false,
                        contentType: false,
                        headers: { 'Authorization': 'Bearer {!$Api.Session_ID}', 'Content-Type': 'application/json' },
                        xhr: function () {
                            var xhr = new window.XMLHttpRequest();
                            xhr.upload.addEventListener("progress", function (evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = parseInt((evt.loaded / evt.total) * 100);
                                    console.log("Upload: " + percentComplete + "% complete")
                                }
                            }, false);
                            return xhr;
                        },
                        success: function (response) {
                            uploaded++
                            callback(null, true)
                        },
                        error: function (errorObj, errorMessage, errorThrown) {
                            callback(errorObj.responseText, false);
                        }
                    });
                });
            }

            var filetoBase64 = function (file, callback) {
                var reader = new FileReader();
                reader.onload = function () {
                    var fileContents = reader.result;
                    var base64Mark = 'base64,';
                    var dataStart = fileContents.indexOf(base64Mark) + base64Mark.length;
                    fileContents = fileContents.substring(dataStart);
                    callback(null, fileContents);
                }
                reader.readAsDataURL(file);
            }
        });
    </script>

    <div style="margin: 30px">
        Author Name:
        <input type="text" id="author" placeholder="Author Name" />
        <br/>
        <br/> Email Address:
        <input type="text" id="email" placeholder="Email Address" />
        <br/>
        <br/> Description:
        <textarea id="description" placeholder="Add a description here"></textarea>
        <br/>
        <br/> Add file:
        <input type="file" id="file" multiple="multiple" />
    </div>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment