With the move to Dynamics 365 version 9.x, many new methods have been added to the Client API. One of the particularly useful ones is the ability to (in a now supported manner) save files directly from Dynamics 365.
A link to the documentation can be found here: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-navigation/openfile
The functionality is fairly simple to use, and requires specifying the following parameters:
• file
- fileContent – String - Base 64 encoded string containing the content for the file.
- filename – String - Name of the file. This does not have to be base 64 encoded.
• fileSize – Number - Size of the file in KB
- While the documentation says this parameter is required, the operation will be successful even if this is not included as the filesystem will automatically determine the size of the file.
• mimeType – String - MIME type of the file
• openFileOptions
- Number – 1 = Open file, 2 = Save file
- At the time of writing this, when testing in both Chrome and IE, the open and save file options appeared to perform exactly the same.
A few instances in which this functionality might come in handy are:
• Saving files that already exist in Dynamics 365:
- Attachments (activitymimeattachment) are files that are saved in the database.
• Saving custom files from Dynamics 365:
- Data that exists in Dynamics 365 can be obtained via queries and put into an appropriate format for download.
• Example use cases:
- Download associated record collections as CSV file
- Format form data and download
- Note above are trivial examples, as they can also be accomplished with Mail Merge and Export to Excel functions.
• Custom data can also be used:
- A JavaScript trace file could be saved to show a log of errors that occurred while processing, which could be handy as this is normally not available to the user (usually only plugin trace files are available)
The openFile method is available through Xrm.Navigation, which means it is available everywhere the Xrm.Navigation object is, including from the main window: _top: main.aspx
Example Code:
Note that the function btoa is also being used: this is a JavaScript function that base 64 encodes a String object.
The above code results in: