How to create progress bar for file upload via the Google Drive API

4

I'm uploading a file to Google Drive through their API. request.Upload(); is delaying with no return. How do I make progress? It can be with for even without graphical interface.

Shipping method:

 public static File UploadFile(DriveService _service, string _uploadFile, string _parent)
    {
        if (System.IO.File.Exists(_uploadFile))
        {
            File body = new File();
            body.Title = System.IO.Path.GetFileName(_uploadFile);
            body.Description = "Teste";
            body.MimeType = GetMimeType(_uploadFile);
            body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

            // monta os bytes
            byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            try
            {
                FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, body.MimeType);
                request.Upload();
                return request.ResponseBody;
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return null;
            }
        }
        else
        {
            Console.WriteLine("File does not exist: " + _uploadFile);
            return null;
        }

    }
    
asked by anonymous 17.06.2015 / 21:02

2 answers

3

You will have to use the event ProgressChanged :

 FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, body.MimeType);
 request.ProgressChanged += Upload_ProgressChanged;
 ....

 private static void Upload_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
 {            
     // calcule aqui a porcentagem a partir do total de bytes do seu arquivo 
     Console.WriteLine("Bytes enviados: " + progress.BytesSent);
 }

Using this event, simply make an account with the total bytes of your file and the BytesSent property of the object received in the event parameter. This makes it easy to use any progress control or even text with the percentage.

However, you will need to upload asynchronously. Change the line:

request.Upload();

To

request.UploadAsync();

Reference: link

    
17.06.2015 / 22:25
1

From the documentation, InsertMediaUpload drift ResumableUpload<TRequest> .

The percentage can be obtained using the GetProgress . Also as in the response of @MarcusVinicius , you can write a callback to send it to a screen or somewhere else. In its example, it is sent to the Console .

    
18.06.2015 / 16:56