How to Get a File (PDF, Image) from MS CRM Table in Base64 Format Using JavaScript?

Get a File (PDF, Image) from MS CRM
Get a File (PDF, Image) from MS CRM

Microsoft Dynamics 365 CRM allows storing files such as PDFs and images in File or Image columns. Retrieving these files in Base64 format using JavaScript can be useful for displaying images, downloading files, or processing data in web applications.

In this article, we will explore how to retrieve a file from a table in Dynamics 365 CRM using JavaScript and Web API and convert it into Base64 format.


Why Use Base64 Format?

Base64 encoding is useful when:

  • You want to display an image without saving it to disk.
  • You need to send a file via API as a string.
  • You want to embed a file directly in an HTML page.


Steps to Retrieve a File in Base64 Format

To retrieve a file from a table in Microsoft Dynamics 365 CRM, follow these steps:

1. Use Xrm.WebApi to Fetch the File Column

The Xrm.WebApi.retrieveRecord function helps fetch data from a CRM table.

2. Extract the File Content in Base64 Format

The response contains the Base64-encoded file, which can be used as needed.

3. Handle Different File Types

Base64 strings can be used to:

  • Display images in <img> elements.
  • Download files using a link.

JavaScript Code Example

function getFileInBase64(entityName, recordId, columnName, mimeType) {
    var apiUrl = `/api/data/v9.0/${entityName}(${recordId})/${columnName}`;

    Xrm.WebApi.online.retrieveRecord(entityName, recordId, `?$select=${columnName}`)
        .then(function (result) {
            if (result[columnName]) {
                console.log("Base64 File Data:", result[columnName]); // Base64 string of the file
                
                // Example: Show as an image (if it's an image file)
                if (mimeType.startsWith("image/")) {
                    let imgElement = document.createElement("img");
                    imgElement.src = `data:${mimeType};base64,` + result[columnName];
                    document.body.appendChild(imgElement);
                } else {
                    // Download as a file (for PDFs, etc.)
                    let link = document.createElement("a");
                    link.href = `data:${mimeType};base64,` + result[columnName];
                    link.download = "downloaded_file";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            } else {
                console.log("No file found in the column.");
            }
        })
        .catch(function (error) {
            console.error("Error retrieving file:", error.message);
        });
}

// Example Usage
var entityName = "account";  // Change to your table name
var recordId = "00000000-0000-0000-0000-000000000000"; // Change to your record GUID
var columnName = "documentbody";  // Change to your file column name
var mimeType = "application/pdf"; // Change based on file type (image/png, application/pdf, etc.)

getFileInBase64(entityName, recordId, columnName, mimeType);

How This Code Works?

Fetch File Data:

  • The Xrm.WebApi.online.retrieveRecord method is used to fetch data.
  • The file content is returned in Base64 format inside the columnName field.

Display Image:

  • If the MIME type starts with "image/", the Base64 data is set as the src of an <img> element.

Download File (PDF, etc.):

  • A temporary anchor (<a>) is created to trigger the file download using the Base64 data.

Use Cases of This Approach

✔️ Displaying user profile images stored in CRM.
✔️ Retrieving and embedding product images on a webpage.
✔️ Downloading stored PDF documents, invoices, or agreements from CRM.

Retrieving files from Dynamics 365 CRM in Base64 format using JavaScript is simple with the Web API. This method allows you to use files directly in web applications without additional storage or processing.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *