Edit Office Documents online in web application using Office365 OneDrive APIs

|
| By Webner

This post is about editing office documents online in a web application interface for users. In this, you will require an office 365 license to use Microsoft graph APIs to edit documents through Onedrive.

To edit MS Word documents online, one of the quick approaches is saving the Word document to OneDrive and use the graph API to open document editing preview online.

We will upload files in the OneDrive folder using OneDrive APIs where we can upload small files up to 4MB as mentioned in the documentation
(https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online) and use a different set of apis for uploading large files (https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online)

All of this process will require Azure Active directory registration of App service which will provide your client id and client secret parameters.
Overall to use Microsoft graph APIs, we must have information of tenant id, client id, client secret of registered Application through Azure Active Directory and proper permissions for one drive to be used by your web application.

It should be configured for graph APIs available through https://graph.microsoft.com.
For the whole process, we need to first get the token for the graph resource. You can follow client_credential, or authorization code flow as per requirements.

You will need to pass “resource” in body. Following is the example of obtaining token using client credential approach-
NameValueCollection postBodyData = new NameValueCollection();
postBodyData.Add("grant_type", “client_credentials”);
postBodyData.Add("client_id", “<Clientid>”);
postBodyData.Add("client_secret", “<ClientSecret>”);
postBodyData.Add("scope", “Directory.Read.All Files.ReadWrite Files.ReadWrite.All
Sites.ReadWrite.All”);
postBodyData.Add("resource", “https://graph.microsoft.com/”);
var webClient = new WebClient() { BaseAddress = <token_endpoint> };
byte[] responseBytes = webClient.UploadValues("", "POST", postBodyData);
string response = Encoding.UTF8.GetString(responseBytes);
string decodedResponse = HttpUtility.UrlDecode(response);
// Deserialize decodedResponse as per your requirements.

For further process, we need a location where files are uploaded in one drive, and based on that we require ids of that folder location and ids of files.

You can get your drive information using Get request API –
https://graph.microsoft.com/<version>/drives

Currently, this post is based on version beta. So based on that URL formation was –
https://graph.microsoft.com/beta/drives (will return info of all present drives with id, create date, drive type, etc.)

For SharePoint sites, get request URL to get information will be
https://graph.microsoft.com/beta/sites

In this example, a SharePoint site drive is taken as an example.
You can select the drive from the site where you want to upload the document and open it for editing to the user through a web application. Check the id of the chosen site from the response returned from https://graph.microsoft.com/beta/sites API. Now find the drives under this site. Choose the drive with driveType “business” and use this id to get children’s items of the drive.

https://graph.microsoft.com/beta/sites/<site-id>/drive/items/<drive-id>/children
If the selected drive is root drive you can simply check drive children as follows :
https://graph.microsoft.com/beta/sites/aed536c1-3c1d-4b1b-b1e7-e4b2cc367935/drive/root/children
Now you can select the folder from your root drive where you are going to upload your files.
Check the id of that folder in response. To upload a file to that specific folder, your upload URL for that folder will then consists of the base format as follows :
https://graph.microsoft.com/beta/sites/<site-id>/drive/items/<folder-id>:
To upload small files upto 4MB, you will use the following approach :
private string UploadSmallFileToOneDrive(string fileName, byte[] fileBytes, string bearerToken)
{
string response = "";
using (var client = new HttpClient())
{
string url =“https://graph.microsoft.com/beta/sites/<site-id>/drive/items/<folder-id>:/<fileName>:/content";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + bearerToken);
var content = new ByteArrayContent(fileBytes);
content.Headers.Add("Content-Length", fileBytes.Length.ToString());
response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}
return response;
}

Parse this response to save the required information which may be required in further steps :
Important information is the id, name, web URL of that file returned in the response.
To upload a large file, you will use the approach which uploads data in parts (in sessions).
https://graph.microsoft.com/beta/sites/<site-id>/drives/items/{folderId}:/{filename}:/createUploadSession

Editing flow:-

We need a document editor URL and that can be obtained from preview API which returns the accessible edit URL of the document based on the post information. For this, use the id of the file returned in the previous response.
https://graph.microsoft.com/beta/sites/<site-id>/drive/items/<file-id>>preview
If we want the document editing to be allowed then we need to post the following data to the preview API. The “allowedit” option does not work in version V1.0. As this post is following the beta version, so it works in that.
dynamic nameValue = new
{
viewer = "office",
allowEdit = true,
chromeless = false
};

Post this information to preview API with scope access token of one drive in headers.
We get the JSON string in response and parse this response.
You will get JSON of the following format:
{
@odata.context: "https://graph.microsoft.com/beta/$metadata#microsoft.graph.itemPreviewInfo"
getUrl: ""
postParameters: null
postUrl: null
}

Here document_preview_url gives you a document preview URL that is editable. You can open this URL in the iframe or popup or in a new tab.

Leave a Reply

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