예제 #1
0
 /// <summary>
 /// Cancel the upload Session
 /// </summary>
 /// <returns>Task to support await of async call.</returns>
 public async Task CancelSessionAsync()
 {
     if (_uploadProvider != null)
     {
         await _uploadProvider.DeleteSession();
     }
 }
예제 #2
0
        private async Task <Microsoft.Graph.DriveItem> doUpload(string filePath, string fileName, string token)
        {
            var graphServiceClient = getClient(token);


            string userFolder = Path.Combine("ForUser", _database.CurrentUser.Uri.ToString());

            string fullUserFolder = Path.Combine(_uploadBasePath, userFolder);

            //string fileName = $"{Guid.NewGuid()}.docx";

            if (!System.IO.Directory.Exists(fullUserFolder))
            {
                System.IO.Directory.CreateDirectory(fullUserFolder);
            }

            string tempPath = Path.Combine(fullUserFolder, Path.GetFileName(filePath));

            System.IO.File.Copy(filePath, tempPath, true);

            FileInfo fileInfo = new FileInfo(tempPath);

            fileInfo.IsReadOnly = false;

            autoOpen(tempPath);


            //	autoOpen(tempPath);
            using (var file = System.IO.File.OpenRead(tempPath))
            {
                var documentFolder = await ODataHelper.PostFolder <OneDriveItem>(GraphApiHelper.GetOneDriveChildrenUrl(), token);


                var uploadSession = await graphServiceClient.Drives[documentFolder.ParentReference.DriveId].Items[documentFolder.Id].ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();

                string ul = uploadSession.UploadUrl += "&$select=Id,ParentReference,WebUrl,WebDavUrl";

                var maxChunkSize = (320 * 1024) * 10;                 // 5000 KB - Change this to your chunk size. 5MB is the default.
                var provider     = new ChunkedUploadProvider(uploadSession, graphServiceClient, file, maxChunkSize);

                try
                {
                    // Setup the chunk request necessities
                    var       chunkRequests     = provider.GetUploadChunkRequests();
                    var       readBuffer        = new byte[maxChunkSize];
                    var       trackedExceptions = new List <Exception>();
                    DriveItem itemResult        = null;

                    //upload the chunks
                    foreach (var request in chunkRequests)
                    {
                        // Do your updates here: update progress bar, etc.
                        // ...
                        // Send chunk request
                        var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);

                        if (result.UploadSucceeded)
                        {
                            itemResult = result.ItemResponse;
                        }
                    }

                    // Check that upload succeeded
                    if (itemResult != null)
                    {
                        return(itemResult);
                    }
                }
                catch
                {
                    await provider.DeleteSession();

                    throw;
                }
            }

            System.IO.File.Delete(tempPath);
            throw new ApplicationException("Upload failed.");
        }
예제 #3
0
        /// <summary>
        /// Uploads a file by splitting it in chunks.
        /// </summary>
        /// <param name="item">The <see cref="PstFile"/> to upload.</param>
        /// <param name="conflictBehaviour">Indicates what to do in case the file already exists</param>
        /// <param name="totalFiles">The total number of files to upload</param>
        /// <param name="file">The current file number</param>
        /// <param name="token">The <see cref="CancellationToken"/> used to check if the task should be cancelled.</param>
        /// <param name="multipleParts">Indicates if the pst/ost file was zipped and therefore split</param>
        /// <param name="totalParts">The total numbers of parts, if the file was split</param>
        /// <param name="part">The current part, if the file was split</param>
        /// <returns>The uploaded file as <see cref="DriveItem"/></returns>
        private async Task <DriveItem> ChunkUpload(PstFile item, string conflictBehaviour, bool multipleParts, int totalFiles, int file,
                                                   CancellationToken token, int totalParts = 1, int part = 1)
        {
            // Setup to check upload speed
            lastAmountOfBytesSent = 0;

            // Create the stream with the file
            using (var stream = new FileStream(item.Path, FileMode.Open))
            {
                // Set the upload path
                var uploadPath = item.Destination + "/" + item.Name;

                // Initialize the chunks provider
                ChunkedUploadProvider provider = null;

                // Will store the uploaded item
                DriveItem itemResult = null;

                // Create upload session
                var uploadSession = await graphClient.Me.Drive.Root.ItemWithPath(uploadPath)
                                    .CreateUploadSession(new DriveItemUploadableProperties()
                {
                    AdditionalData = new Dictionary <string, object>
                    {
                        { "@microsoft.graph.conflictBehavior", conflictBehaviour }
                    }
                })
                                    .Request()
                                    .PostAsync(token);

                // Get the chunks provider
                provider = new ChunkedUploadProvider(uploadSession, graphClient, stream, UploadChunkSize);

                // Setup the chunk request necessities
                var chunkRequests = provider.GetUploadChunkRequests();
                //var readBuffer = new byte[UploadChunkSize];

                // Initialize counters for progress
                var maximum = chunkRequests.Count();
                var i       = 1;

                // Upload the chunks
                await Task.Run(async() =>
                {
                    foreach (var request in chunkRequests)
                    {
                        // Delete session and throw cancellation if requested
                        if (token.IsCancellationRequested)
                        {
                            if (provider != null)
                            {
                                await provider.DeleteSession();
                            }
                            token.ThrowIfCancellationRequested();
                        }

                        // Send chunk request
                        //var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, new List<Exception>());
                        var result = await provider.GetChunkRequestResponseAsync(request, new List <Exception>());

                        // Update the itemProgressBar and UI
                        var currentValue = Math.Round((i / (double)maximum) * 100);
                        await Dispatcher.InvokeAsync(() =>
                        {
                            itemProgressBar.Value = currentValue;

                            itemProgressTextBlock.Text = multipleParts
                                ? "Uploading file " + file + " of " + totalFiles + ": " + item.Name + " | part " +
                                                         part + "/" + totalParts + "... (" + itemProgressBar.Value.ToString("0") + "%)"
                                : "Uploading file " + file + " of " + totalFiles + ": " + item.Name + "... (" +
                                                         itemProgressBar.Value.ToString("0") + "%)";
                        });

                        // Increment counter
                        i++;

                        if (result.UploadSucceeded)
                        {
                            itemResult = result.ItemResponse;
                        }
                    }
                }, token);

                return(itemResult);
            }
        }