1. 程式人生 > >UWP 使用OneDrive雲存儲2.x api(二)【全網首發】

UWP 使用OneDrive雲存儲2.x api(二)【全網首發】

back existing ace -s -c file school sync sqlite

接上一篇 http://www.cnblogs.com/hupo376787/p/8032146.html

上一篇提到為了給用戶打造一個完全無縫銜接的最佳體驗,UWP開發者最好也要實現App設置和數據的跨平臺

分析了數據漫遊和OneDrive的優缺點,結合自己App實際需要,我選擇了OneDrive。

畢竟數據漫遊100KB不夠用啊。。。

這一次給大家我千辛萬苦找來的、非常簡單的使用OneDrive 2.x api使用方法。

那就是隱藏在官方UWP Community Toolkit Sample App中的OneDrive Service中

技術分享圖片

我覺得平時我看這個App已經夠多了,以前也瞄過一眼這個OneDrive Service,但是在真真使用它的時候,偏偏想不起來了。

我用過這裏面的Grid Splitter、Markdown Textbox、RadialProgressBar、等等太多了

這是一個非常好的例子,商店有下載,gayhub也有源代碼

不得不說,微軟開發這個App的人員非常偉大了。。。哈哈哈??

下面就結合我自己的【微識別/WeRecognition】代碼來和大家說一下。

1. 授權

要訪問OneDrive,首先需要授權。

授權有三種方式:

OnlineId,最簡單,我就用這個,也是推薦UWP開發者使用的


Microsoft account with client id

Work or school account with client id

private OneDriveStorageFolder _appFolder = null;這個用來獲取OneDrive下面的應用文件夾

        private async Task SigninAsync(int indexProvider = 0, string appClientId = null)
        {
            if (!IsInternetAvailable())
                return;

            ShowBusy(true);
            try
            {
                
// OnlineId if (indexProvider == 0) { OneDriveService.Instance.Initialize(); } //Microsoft account with client id else if (indexProvider == 1) { OneDriveService.Instance.Initialize(appClientId, AccountProviderType.Msa, OneDriveScopes.AppFolder | OneDriveScopes.ReadWrite); } //Work or school account with client id else if (indexProvider == 2) { OneDriveService.Instance.Initialize(appClientId, AccountProviderType.Adal); } if (await OneDriveService.Instance.LoginAsync()) { _appFolder = await OneDriveService.Instance.AppRootFolderAsync(); ShowBusy(false); } else { ShowBusy(false); throw new Exception("Unable to sign in"); } } catch (ServiceException serviceEx) { var dialog = new MessageDialog(serviceEx.Message, "Error!"); await dialog.ShowAsync(); ShowBusy(false); } catch (Exception ex) { var dialog = new MessageDialog(ex.Message, "Error!"); await dialog.ShowAsync(); ShowBusy(false); } finally { ShowBusy(false); } }

註意:用的時候,最好加上上面捕捉的那些異常,以防萬一。

接下來無非就是,上傳下載文件咯。【我沒有做別的一些操作,比如在OneDrive上新建文件(夾),或者縮略圖等,你可以自行看那個App說明】

我不想把簡單的事情搞得復雜,這個團隊做的也是這樣,能簡單就簡單。不信你上傳的代碼

上傳

                var size = await file.GetBasicPropertiesAsync();
                if (size.Size >= 4 * 1024 * 1024)
                    await OneDriveServiceHelper.UploadLargeFileAsync(file, strBackupName, CreationCollisionOption.ReplaceExisting, _appFolder);
                else
                    await OneDriveServiceHelper.UploadSimpleFileAsync(file, strBackupName, CreationCollisionOption.ReplaceExisting, _appFolder);

不過這要區分一下是不是超過4M,兩種上傳方式,用我的代碼判斷一下即可。

具體為啥區分,請去看官方gayhub上面的Issues討論。

兩個函數的原型

UploadSimpleFileAsync

        public static async Task UploadSimpleFileAsync(OneDriveStorageFolder folder)
        {
            try
            {
                if (folder != null)
                {
                    var selectedFile = await OpenLocalFileAsync();
                    if (selectedFile != null)
                    {
                        using (var localStream = await selectedFile.OpenReadAsync())
                        {
                            var fileCreated = await folder.CreateFileAsync(selectedFile.Name, CreationCollisionOption.GenerateUniqueName, localStream);
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(ex.Message);
            }
            catch (ServiceException graphEx)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(graphEx.Error.Message);
            }
            catch (Exception ex)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(ex.Message);
            }
            finally
            {
                
            }
        }

UploadLargeFileAsync

public static async Task UploadLargeFileAsync(OneDriveStorageFolder folder)
        {
            try
            {
                if (folder != null)
                {
                    var selectedFile = await OpenLocalFileAsync();
                    if (selectedFile != null)
                    {
                        using (var localStream = await selectedFile.OpenReadAsync())
                        {
                            // If the file exceed the Maximum size (ie 4MB)
                            var largeFileCreated = await folder.UploadFileAsync(selectedFile.Name, localStream, CreationCollisionOption.GenerateUniqueName, 320 * 1024);
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(ex.Message);
            }
            catch (ServiceException graphEx)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(graphEx.Error.Message);
            }
            catch (Exception ex)
            {
                await OneDriveServiceHelper.DisplayMessageAsync(ex.Message);
            }
            finally
            {
                
            }
        }

你可能註意到了,官方的函數參數和我用的不一樣,是的。我重新封裝了。

官方的是var selectedFile = await OpenLocalFileAsync();,需要手動選擇文件。在我的場景裏面,是自動選擇數據庫文件上傳的,讓用戶選擇,就不合適了

下載

                var remoteFile = await _appFolder.GetFileAsync(strBackupName);
                using (var remoteStream = await remoteFile.OpenAsync())
                {
                    byte[] buffer = new byte[remoteStream.Size];
                    var localBuffer = await remoteStream.ReadAsync(buffer.AsBuffer(), (uint)remoteStream.Size, InputStreamOptions.ReadAhead);
                    var localFolder = ApplicationData.Current.LocalFolder;
                    var myLocalFile = await localFolder.CreateFileAsync(SQLiteHelper.FaceDbName, CreationCollisionOption.ReplaceExisting);
using (var localStream = await myLocalFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await localStream.WriteAsync(localBuffer);
                        await localStream.FlushAsync();
                        TipServices.TipDataDownloadFromCloudComplete();
                    }

下載不區分什麽大小文件,很簡單的

=================================================================================

總結

UWP本來就是小眾,資料少之又少,我走過了坑,記錄下來,對以後用到OneDrive 開發的有所幫助。

使用OneDrive Api 2.x流程如下

  1. 註冊應用以獲取應用 ID。
  2. 使用令牌流或代碼流通過指定的作用域讓用戶登錄。就是上面的 SigninAsync函數
  3. 上傳下載操作
  4. 註銷用戶(可選)。

以上就是在我的【微識別/WeRecognition】場景裏面使用的實際代碼分享,如有不足之處,敬請指正。謝謝。

UWP 使用OneDrive雲存儲2.x api(二)【全網首發】