robledosm/OneDriveForBusiness-Explorer-MVC

语言: JavaScript

git: https://github.com/robledosm/OneDriveForBusiness-Explorer-MVC

此示例使用Office 365 API客户端库演示针对OneDrive for Business的基本操作...
This sample uses the Office 365 APIs client libraries to demonstrate basic operations against OneDrive for Business s…
README.md (中文)

适用于ASP.NET MVC的OneDrive for Business入门项目

目录 - 概述 - 先决条件和配置 - 快速查看SSO身份验证代码 - 快速查看OneDriveExplorerController.cs代码 - 快速查看JavaScript代码 - 感兴趣的项目文件 - 执照 - 问题和评论

概观

此示例使用Office 365 API客户端库从单租户ASP.NET MVC5应用程序演示Office 365中针对OneDrive for Business服务端点的基本操作。

以下是您可以使用此示例执行的操作:

  • 读取文件和文件夹
  • 浏览文件夹
  • 下载文件
  • 上传文件

先决条件和配置

此示例需要以下内容:

  • Visual Studio 2013 Update 3。
  • Microsoft Office 365 API工具。
  • Office 365开发人员站点或其他Office 365租户。
  • 您的计算机上启用了Microsoft IIS。

注册应用程序并配置示例以使用Office 365 API

您可以通过Visual Studio的Office 365 API工具(自动执行注册过程)来完成此操作。在继续操作之前,请务必从Visual Studio库下载并安装Office 365 API工具。

  1. 建立项目。这将恢复此解决方案的NuGet包。
  2. 在Solution Explorer窗口中,选择OneDriveForBusiness.MVC项目 - >添加 - >已连接服务。
  3. 将出现“服务管理器”窗口。选择Office 365 - > Office 365 API,然后选择注册您的应用程序链接。
  4. 如果您之前未登录,则会出现登录对话框。输入Office 365租户管理员的用户名和密码。我们建议您使用Office 365开发人员站点。通常,此用户名将遵循{username}@{tenant}.onmicrosoft.com模式。如果您没有开发者网站,您可以获得免费的开发者网站作为MSDN福利的一部分或注册免费试用。请注意,用户必须是租户管理员用户 - 但对于作为Office 365开发人员站点的一部分创建的租户,可能已经是这种情况。开发者帐户通常仅限于一个用户。
  5. 登录后,您将看到所有服务的列表。最初,不会选择任何权限,因为应用程序尚未注册以使用任何服务。
  6. 要注册此示例中使用的服务,请选择以下权限,然后选择“权限”链接以设置以下权限:
  7. (文件) - 读取和写入文件(写入)
  8. (用户和组) - 登录并阅读您的个人资料(阅读)
  9. 在Services Manager窗口中选择App Properties链接。将此应用程序提供给单个组织。
  10. 在“服务管理器”窗口中选择“确定”后,用于连接到Office 365 REST API的程序集将添加到项目中,并且以下条目将添加到web.config中的appSettings:ClientId,ClientSecret,AADInstance和TenantId。您可以使用租户名称作为TenantId设置的值,而不是使用租户标识符。
  11. 构建解决方案。 Nuget包将添加到您的项目中。现在,您已准备好运行解决方案并使用组织帐户登录Office 365。

快速查看SSO身份验证代码

项目中的身份验证启动类App_Start / Startup.Auth.cs包含Azure AD身份验证的启动逻辑。这些类演示了如何构造持久性ADAL令牌缓存并将其用于存储令牌。您可以在以下文件中看到令牌缓存实现:    - ADAL / ADALTokenCache.cs    - ADAL / ADALDbContext.cs    - ADAL / Model / UserTokenCache.cs

要求访问控制器的身份验证

将Authorize属性应用于项目中的所有控制器将要求用户在访问这些控制器之前进行身份验证。要允许匿名访问控制器,请从控制器中删除此属性。如果要在更细粒度级别设置权限,请将该属性应用于需要授权的每个方法,而不是将其应用于控制器类。

快速查看OneDriveExplorerController.cs代码

获取SharePoint API客户端

获取SharePointClient对象。您可以从使用SharePoint客户端的其他方法调用此代码。

private static async Task<SharePointClient> GetSharePointClient()
{
    string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier".Value;
    string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

    AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

    DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
            async () =>
            {
                var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                return authResult.AccessToken;
            });

    CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability);
    SharePointClient client = new SharePointClient(capability.ServiceEndpointUri,
        async () =>
        {
            var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

            return authResult.AccessToken;
        });
    return client;
}

浏览文件夹和文件

返回OneDriveItemViewModel的列表,如果folderId为null或空字符串,则将使用根文件夹中的对象填充列表。

List<OneDriveItemViewModel> oneDriveItems = new List<OneDriveItemViewModel>();
SharePointClient client = await GetSharePointClient();
if (string.IsNullOrEmpty(folderId))
{
  var filesResult = await client.Files.ExecuteAsync();
  do
  {
      var files = filesResult.CurrentPage;
      foreach (var file in files)
      {
          string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty;
          oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName });
      }
      filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult();
  } while (filesResult != null);
}
else
{
  var filesResult = await client.Files.GetById(folderId).ToFolder().Children.ExecuteAsync();
  do
  {
      var files = filesResult.CurrentPage;
      foreach (var file in files)
      {
          string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty;
          oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName });
      }
      filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult();
  } while (filesResult != null);
}

下载文件

从OneDrive for Business下载文件作为流。

SharePointClient client = await GetSharePointClient();
var file = client.Files.GetById(fileId).ToFile();
using (Stream stream = await file.DownloadAsync())
{
    using (MemoryStream ms = new MemoryStream())
    {
        stream.Seek(0, SeekOrigin.Begin);
        stream.CopyTo(ms);
        byte[] buffer = ms.ToArray();

        var fileData = await file.ExecuteAsync();
        Response.Clear();
        Response.ContentType = GetContentType(fileData.Name);
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileData.Name, System.Text.Encoding.UTF8));
        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.OutputStream.Write(buffer, 0, buffer.Length);
        Response.Flush();
    }
}

上传文件

将流作为文件上载到OneDrive for Business,删除该文件(如果已存在)。

SharePointClient client = await GetSharePointClient();
var fileName = Request.Headers["X-File-Name"];
try
{
    // First check if a file with the same name already exists. If it exists, delete it.
    var item = await client.Files.GetByPathAsync(fileName);
    await item.DeleteAsync();
}
catch
{
    //there is no file with the same name, swallow the error and continue
}

var oneDriveFile = new Microsoft.Office365.SharePoint.FileServices.File
{
    Name = fileName
};
await client.Files.AddItemAsync(oneDriveFile);
await client.Files.GetById(oneDriveFile.Id).ToFile().UploadAsync(Request.InputStream);

快速查看JavaScript代码

浏览文件夹和文件

从OneDriveExplorer控制器的List方法获取文件和文件夹列表。

function loadFolder(folderId) {
  var dfd = $.Deferred();
  $('.loading-container').removeClass('loading-inactive');
  tbody.empty();
  $.ajax({
      url: '@Url.Action("List", "OneDriveExplorer")',
      data: { folderId: folderId },
      cache: false,
      method: 'POST',
      dataType: 'json',
      success: function (data) {
          if (data.success === true) {
              var rows = '';
              $.each(data.items, function (idx, item) {
                  rows += '<tr data-element-id="' + item.Id + '" data-element-name="' + item.Name + '" data-element-size="' + item.Size + '">' +
                                     '<td>' + createMenu(item.Type, item.Extension) + '</td>' +
                                     '<td>' + item.Name + '</td>' +
                                     '<td>' + item.Creator + '</td>' +
                                     '<td align="right">' + (item.Type === "Folder" ? '' : getReadableFileSizeString(item.Size)) + '</td>' +
                                 '</tr>';
              });
              tbody.append(rows);
              tbody.find('tr').dblclick(function (e) {
                  var selectedItem = getSelectedItem();
                  switch (selectedItem.type) {
                      case "Folder": //open folder
                          openFolder();
                          break;
                      case "File": //download file
                          downloadFile();
                      default:
                          break;
                  }
              });
              tbody.find('tr').click(function (e) {
                  var id = $(this).attr('data-element-id');
                  tbody.find('tr.active').removeClass('active').removeClass('selectedRow');
                  tbody.find('tr[data-element-id="' + id + '"]').addClass('active').addClass('selectedRow');
              });
              dfd.resolve();
          }
          else {
              if (data.message) {
                  alert(data.message);
              }
              dfd.reject(data);
          }

      },
      complete: function () {
          $('.loading-container').addClass('loading-inactive');
      }
  });
  return dfd.promise();
}

下载文件

在从OneDrive for Business下载文件之前要求用户进行确认。

function downloadFile() {
  var selectedItem = getSelectedItem();
  if (selectedItem.type === "File") {
      var confirm = bootbox.dialog({
          title: 'Confirm',
          message: 'Are you sure you want to download ' + selectedItem.name + '?',
          backdrop: true,
          show: false,
          buttons: {
              No: {
                  callback: function () {
                      return true;
                  }
              },
              Yes: {
                  className: 'btn-success',
                  callback: function () {
                      var url = '@Url.Action("Download", "OneDriveExplorer")?fileId=' + selectedItem.id;
                      window.open(url, "_blank");
                      return true;
                  }
              }
          }
      });
      confirm.find('.modal-dialog').addClass('modal-md');
      confirm.modal('show');
  }
}

上传文件

在使用XMLHttpRequest()将文件上载到OneDrive for Business之前,要求用户进行确认。

uploadButton.click(function (e) {
  var fileSelect = document.getElementById("file-select");
  var files = fileSelect.files;
  if (files.length > 0) {
      var confirm = bootbox.dialog({
          title: 'Confirm',
          message: 'Are you sure you want to upload the selected file?',
          backdrop: true,
          show: false,
          buttons: {
              No: {
                  callback: function () {
                      return true;
                  }
              },
              Yes: {
                  className: 'btn-success',
                  callback: function () {
                      $('.loading-container').removeClass('loading-inactive');
                      var file = files[0];
                      var xhr = new XMLHttpRequest();

                      // File uploaded
                      xhr.addEventListener("load", function () {
                          //upload complete
                          $('.loading-container').addClass('loading-inactive');
                      }, false);


                      xhr.open("POST", "@Url.Action("Upload", "OneDriveExplorer")", true);

                      // Set headers
                      xhr.setRequestHeader("Content-Type", "multipart/form-data");
                      xhr.setRequestHeader("X-File-Name", file.name);

                      // Send the file
                      xhr.send(file);
                  }
              }
          }
      });
      confirm.find('.modal-dialog').addClass('modal-md');
      confirm.modal('show');
  }
  else
  {
      bootbox.alert({
          title: 'Missing file',
          message: 'Please, select a file to upload'
      });
  }
});

感兴趣的项目文件

控制器

  • OneDriveExplorerController.cs

楷模

  • OneDrive项目ViewModel.cs

查看

  • OneDriveExplorer / Index.cshtml

Utils文件夹

  • SettingsHelper.cs

此示例使用Bootbox.js呈现对话框,使用XMLHttpRequest上载文件

问题和评论

我们很乐意收到您对OneDriveForBusiness-Explorer-MVC项目的反馈。您可以在此存储库的“问题”部分中将您的问题和建议发送给我们。

版权

版权所有(c)Lumen21,INC。保留所有权利。

本文使用googletrans自动翻译,仅供参考, 原文来自github.com

en_README.md

OneDrive for Business starter project for ASP.NET MVC

Table of Contents
- Overview
- Prerequisites and Configuration
- Quick Look at the SSO Authentication Code
- Quick Look at the the OneDriveExplorerController.cs Code
- Quick Look at the the JavaScript Code
- Project files of interest
- License
- Questions and Comments

Overview

This sample uses the Office 365 APIs client libraries to demonstrate basic operations against OneDrive for Business service endpoint in Office 365 from a single-tenant ASP.NET MVC5 application.

Below are the operations that you can perform with this sample:

  • Read files and folders
  • Browse folders
  • Download files
  • Upload files

Prerequisites and Configuration

This sample requires the following:

Register app and configure the sample to consume Office 365 API

You can do this via the Office 365 API Tools for Visual Studio (which automates the registration process). Be sure to download and install the Office 365 API tools from the Visual Studio Gallery before you proceed any further.

  1. Build the project. This will restore the NuGet packages for this solution.
  2. In the Solution Explorer window, choose OneDriveForBusiness.MVC project -> Add -> Connected Service.
  3. A Services Manager window will appear. Choose Office 365 -> Office 365 APIs and select the Register your app link.
  4. If you haven't signed in before, a sign-in dialog box will appear. Enter the user name and password for your Office 365 tenant admin. We recommend that you use your Office 365 Developer Site. Often, this user name will follow the pattern {username}@{tenant}.onmicrosoft.com. If you do not have a developer site, you can get a free Developer Site as part of your MSDN Benefits or sign up for a free trial. Be aware that the user must be a Tenant Admin user—but for tenants created as part of an Office 365 Developer Site, this is likely to be the case already. Also developer accounts are usually limited to one user.
  5. After you're signed in, you will see a list of all the services. Initially, no permissions will be selected, as the app is not registered to consume any services yet.
  6. To register for the services used in this sample, choose the following permissions, and select the Permissions link to set the following permissions:
  7. (Files) - Read and write to your files (Write)
  8. (Users and Groups) – Sign you in and read your profile (Read)
  9. Choose the App Properties link in the Services Manager window. Make this app available to a Single Organization.
  10. After selecting OK in the Services Manager window, assemblies for connecting to Office 365 REST APIs will be added to your project and the following entries will be added to your appSettings in the web.config: ClientId, ClientSecret, AADInstance, and TenantId. You can use your tenant name for the value of the TenantId setting instead of using the tenant identifier.
  11. Build the solution. Nuget packages will be added to you project. Now you are ready to run the solution and sign in with your organizational account to Office 365.

Quick Look at the SSO Authentication Code

The authentication startup class, App_Start/Startup.Auth.cs in the project contains the startup logic for Azure AD authentication. These classes demonstrate how a persistent ADAL token cache can be constructed and used to store tokens. You can see the token cache implementation in the following files:
- ADAL/ADALTokenCache.cs
- ADAL/ADALDbContext.cs
- ADAL/Model/UserTokenCache.cs

Requiring authentication to access controllers

Applying Authorize attribute to all controllers in your project will require the user to be authenticated before accessing these controllers. To allow the controller to be accessed anonymously, remove this attribute from the controller. If you want to set the permissions at a more granular level, apply the attribute to each method that requires authorization instead of applying it to the controller class.

Quick Look at the the OneDriveExplorerController.cs Code

Getting the SharePoint API Client

Get the SharePointClient object. You can call this code from other methods that use the SharePoint client.

private static async Task<SharePointClient> GetSharePointClient()
{
    string signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier".Value;
    string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

    AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

    DiscoveryClient discovery = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
            async () =>
            {
                var authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                return authResult.AccessToken;
            });

    CapabilityDiscoveryResult capability = await discovery.DiscoverCapabilityAsync(SettingsHelper.Capability);
    SharePointClient client = new SharePointClient(capability.ServiceEndpointUri,
        async () =>
        {
            var authResult = await authContext.AcquireTokenSilentAsync(capability.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

            return authResult.AccessToken;
        });
    return client;
}

Browsing folders and files

Returns a list of OneDriveItemViewModel, if folderId is a null or an empty string, the list will be populated with objects from the root folder.

List<OneDriveItemViewModel> oneDriveItems = new List<OneDriveItemViewModel>();
SharePointClient client = await GetSharePointClient();
if (string.IsNullOrEmpty(folderId))
{
  var filesResult = await client.Files.ExecuteAsync();
  do
  {
      var files = filesResult.CurrentPage;
      foreach (var file in files)
      {
          string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty;
          oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName });
      }
      filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult();
  } while (filesResult != null);
}
else
{
  var filesResult = await client.Files.GetById(folderId).ToFolder().Children.ExecuteAsync();
  do
  {
      var files = filesResult.CurrentPage;
      foreach (var file in files)
      {
          string extension = (file.Type == "File") ? System.IO.Path.GetExtension(file.Name).Split('.')[1] : string.Empty;
          oneDriveItems.Add(new OneDriveItemViewModel { Id = file.Id, Name = file.Name, Size = file.Size, Type = file.Type, Extension = extension, Creator = file.CreatedBy.User.DisplayName });
      }
      filesResult = filesResult.GetNextPageAsync().GetAwaiter().GetResult();
  } while (filesResult != null);
}

Downloading files

Download a file from OneDrive for Business as a Stream.

SharePointClient client = await GetSharePointClient();
var file = client.Files.GetById(fileId).ToFile();
using (Stream stream = await file.DownloadAsync())
{
    using (MemoryStream ms = new MemoryStream())
    {
        stream.Seek(0, SeekOrigin.Begin);
        stream.CopyTo(ms);
        byte[] buffer = ms.ToArray();

        var fileData = await file.ExecuteAsync();
        Response.Clear();
        Response.ContentType = GetContentType(fileData.Name);
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileData.Name, System.Text.Encoding.UTF8));
        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.OutputStream.Write(buffer, 0, buffer.Length);
        Response.Flush();
    }
}

Uploading files

Uploads a stream as a file to OneDrive for Business deleting the file if it alrady exists.

SharePointClient client = await GetSharePointClient();
var fileName = Request.Headers["X-File-Name"];
try
{
    // First check if a file with the same name already exists. If it exists, delete it.
    var item = await client.Files.GetByPathAsync(fileName);
    await item.DeleteAsync();
}
catch
{
    //there is no file with the same name, swallow the error and continue
}

var oneDriveFile = new Microsoft.Office365.SharePoint.FileServices.File
{
    Name = fileName
};
await client.Files.AddItemAsync(oneDriveFile);
await client.Files.GetById(oneDriveFile.Id).ToFile().UploadAsync(Request.InputStream);

Quick Look at the the JavaScript Code

Browse folders and files

Gets the list of files and folders from the List method of the OneDriveExplorer Controller.

function loadFolder(folderId) {
  var dfd = $.Deferred();
  $('.loading-container').removeClass('loading-inactive');
  tbody.empty();
  $.ajax({
      url: '@Url.Action("List", "OneDriveExplorer")',
      data: { folderId: folderId },
      cache: false,
      method: 'POST',
      dataType: 'json',
      success: function (data) {
          if (data.success === true) {
              var rows = '';
              $.each(data.items, function (idx, item) {
                  rows += '<tr data-element-id="' + item.Id + '" data-element-name="' + item.Name + '" data-element-size="' + item.Size + '">' +
                                     '<td>' + createMenu(item.Type, item.Extension) + '</td>' +
                                     '<td>' + item.Name + '</td>' +
                                     '<td>' + item.Creator + '</td>' +
                                     '<td align="right">' + (item.Type === "Folder" ? '' : getReadableFileSizeString(item.Size)) + '</td>' +
                                 '</tr>';
              });
              tbody.append(rows);
              tbody.find('tr').dblclick(function (e) {
                  var selectedItem = getSelectedItem();
                  switch (selectedItem.type) {
                      case "Folder": //open folder
                          openFolder();
                          break;
                      case "File": //download file
                          downloadFile();
                      default:
                          break;
                  }
              });
              tbody.find('tr').click(function (e) {
                  var id = $(this).attr('data-element-id');
                  tbody.find('tr.active').removeClass('active').removeClass('selectedRow');
                  tbody.find('tr[data-element-id="' + id + '"]').addClass('active').addClass('selectedRow');
              });
              dfd.resolve();
          }
          else {
              if (data.message) {
                  alert(data.message);
              }
              dfd.reject(data);
          }

      },
      complete: function () {
          $('.loading-container').addClass('loading-inactive');
      }
  });
  return dfd.promise();
}

Downloading files

Asks the user for confirmation before downloading the file from OneDrive for Business.

function downloadFile() {
  var selectedItem = getSelectedItem();
  if (selectedItem.type === "File") {
      var confirm = bootbox.dialog({
          title: 'Confirm',
          message: 'Are you sure you want to download ' + selectedItem.name + '?',
          backdrop: true,
          show: false,
          buttons: {
              No: {
                  callback: function () {
                      return true;
                  }
              },
              Yes: {
                  className: 'btn-success',
                  callback: function () {
                      var url = '@Url.Action("Download", "OneDriveExplorer")?fileId=' + selectedItem.id;
                      window.open(url, "_blank");
                      return true;
                  }
              }
          }
      });
      confirm.find('.modal-dialog').addClass('modal-md');
      confirm.modal('show');
  }
}

Uploading files

Asks the user for confirmation before uploading a file to OneDrive for Business using XMLHttpRequest().

uploadButton.click(function (e) {
  var fileSelect = document.getElementById("file-select");
  var files = fileSelect.files;
  if (files.length > 0) {
      var confirm = bootbox.dialog({
          title: 'Confirm',
          message: 'Are you sure you want to upload the selected file?',
          backdrop: true,
          show: false,
          buttons: {
              No: {
                  callback: function () {
                      return true;
                  }
              },
              Yes: {
                  className: 'btn-success',
                  callback: function () {
                      $('.loading-container').removeClass('loading-inactive');
                      var file = files[0];
                      var xhr = new XMLHttpRequest();

                      // File uploaded
                      xhr.addEventListener("load", function () {
                          //upload complete
                          $('.loading-container').addClass('loading-inactive');
                      }, false);


                      xhr.open("POST", "@Url.Action("Upload", "OneDriveExplorer")", true);

                      // Set headers
                      xhr.setRequestHeader("Content-Type", "multipart/form-data");
                      xhr.setRequestHeader("X-File-Name", file.name);

                      // Send the file
                      xhr.send(file);
                  }
              }
          }
      });
      confirm.find('.modal-dialog').addClass('modal-md');
      confirm.modal('show');
  }
  else
  {
      bootbox.alert({
          title: 'Missing file',
          message: 'Please, select a file to upload'
      });
  }
});

Project files of interest

Controllers

Models

Views

Utils Folder

This sample uses Bootbox.js to render dialog boxes and XMLHttpRequest to upload files

Questions and Comments

We'd love to get your feedback on the OneDriveForBusiness-Explorer-MVC project. You can send your questions and suggestions to us in the Issues section of this repository.

Copyright

Copyright (c) Lumen21, INC. All rights reserved.