Upload JSON Object as a File into Office 365 using JavaScript (JSOM)

Introduction

This post is intended to explain how to convert and upload a JSON Object into a SharePoint library using JavaScript Client Object Model.

That approach will be valid using the code inside a SharePoint Web Part, will not be valid for SP Apps or JavaScript applications running outside of SharePoint context.

Here you can see the code:

(function () {
var Utils = (function () {
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
// http://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function JSONObjectToSPFileBinary(jsonObject) {
// Convert JSON object to File
// 1. Convert JSON object to string
var jsonString = JSON.stringify(jsonObject, null, 0);
// 2. Convert string to Base64 Encoded Byte Array
var base64EncodedArray = b64EncodeUnicode(jsonString);
// 3. Crate SP.Base64EncodedByteArray with the content
var content = new SP.Base64EncodedByteArray(base64EncodedArray); //base64 encoding
// Reverse: b64DecodeUnicode(content.toBase64String())
// End Convert JSON object to File
return content;
}
return {
b64EncodeUnicode: b64EncodeUnicode,
b64DecodeUnicode: b64DecodeUnicode,
JSONObjectToSPFileBinary: JSONObjectToSPFileBinary };
})();
var siteUrlFromRoot = "rootSubsite";
var libraryTitle = "Documents";
// Take into account that json format is not allowed on SPO, so use .js format instead:
// https://sharepoint.uservoice.com/forums/329220-sharepoint-dev-platform/suggestions/15146862-allow-json-files-to-be-stored-in-sharepoint-onlin
var fileName = "site_date.js";
var jsonObject = { data1: "blah", sample: "bloh" };
if (window
&& "_spPageContextInfo" in window
&& "siteServerRelativeUrl" in _spPageContextInfo
&& "SP" in window
&& "ClientContext" in SP
&& "FileCreationInformation" in SP) {
// Connect to the given Site Url
var baseRelativeUrl = _spPageContextInfo.siteServerRelativeUrl;
var destinationSiteUrl = baseRelativeUrl + "/" + siteUrlFromRoot;
var ctx = new SP.ClientContext(destinationSiteUrl);
// Create SP File from JSON Object
var content = Utils.JSONObjectToSPFileBinary(jsonObject);
var fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(fileName);
fileCreateInfo.set_overwrite(true);
fileCreateInfo.set_content(content);
// Upload the file to the root folder of the document library
var parentList = ctx.get_web().get_lists().getByTitle(libraryTitle);
var file = parentList.get_rootFolder().get_files().add(fileCreateInfo);
var fileListItem = file.get_listItemAllFields();
ctx.load(fileListItem);
ctx.executeQueryAsync(
function () {
console.log(fileListItem);
},
function (sender, args) {
console.log('Error: ' + args.get_message());
}
);
} else {
console.warn("There is no _spPageContextInfo nor SP");
}
})();

Browser Coverage

I tested it in Chrome 56 and Internet Explorer 11 and it worked.

Read more…

IMPORTANT: If you want to upload other kind of documents (more that 2 MB). Then I recommend you take a look to this post: http://sharepointcookies.com/2017/02/programmatically-uploading-large-files-client-side-to-sharepoint-2013/ from my colleague Kev.

Please, write a comment if that’s not working in your specific scenario!

 

Author: José Quinto
Link: https://blog.josequinto.com/2017/03/03/upload-json-object-as-a-file-into-office-365-using-javascript-jsom/
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.