Thursday 16 July 2015

Downloading files from OneDrive using the Office 365 API (MVC add-in)

For this example I used the "Office 365 Starter Project for ASP.NET MVC" developed by Microsoft, which you can find here, including all the instructions to set it up.

This sample uses "the Office 365 API Tools to demonstrate basic operations against the Calendar, Contacts, and Mail service endpoints in Office 365 from a single-tenant ASP.NET MVC application.", so when you click in "My Files" button, you get a list of all files and folders within your personal OneDrive and the capability of deleting them. 

What I'm going to demonstrate is how to extend those capabilities, by adding a new link (Download) which will allow you to download the files you want. 

First, we have to create the method to download the file in our FileOperations class, located inside the "Helpers" folder.























Then, we have to create our "Download" action in the file controller. This action will be a FileStreamResult, as we want to send binary content using a Stream instance. 
Finally we will return the result of type File, passing the Stream instance and the file name. 

Note: In order to dynamically retrieve the item content type, we will use MimeMapping.GetMimeMapping method.



















To finish, we need to edit the view and add an action link to our controller. This action will be displayed only when the item is a file.














... The result:



























Happy coding ;)

No comments:

Post a Comment