How to track progress of async file upload to azure storage

后端 未结 4 719
我寻月下人不归
我寻月下人不归 2020-12-03 01:56

Is there way to track the file upload progress to an Azure storage container? I am trying to make a console application for uploading data to Azure using C#.

My c

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 02:39

    The below code uses Azure Blob Storage SDK v12. Reference link: https://www.craftedforeveryone.com/upload-or-download-file-from-azure-blob-storage-with-progress-percentage-csharp/

    public void UploadBlob(string fileToUploadPath)
    {
        var file = new FileInfo(fileToUploadPath);
        uploadFileSize = file.Length; //Get the file size. This is need to calculate the file upload progress
    
        //Initialize a progress handler. When the file is being uploaded, the current uploaded bytes will be published back to us using this progress handler by the Blob Storage Service
        var progressHandler = new Progress();
        progressHandler.ProgressChanged += UploadProgressChanged;
    
        var blob = new BlobClient(connectionString, containerName, file.Name); //Initialize the blob client
        blob.Upload(fileToUploadPath, progressHandler: progressHandler); //Make sure to pass the progress handler here
    
    }
    
    private void UploadProgressChanged(object sender, long bytesUploaded)
    {
        //Calculate the progress and update the progress bar.
        //Note: the bytes uploaded published back to us is in long. In order to calculate the percentage, the value has to be converted to double. 
        //Auto type casting from long to double happens here as part of function call
        Console.WriteLine(GetProgressPercentage(uploadFileSize, bytesUploaded));
    }
    
    private double GetProgressPercentage(double totalSize,double currentSize)
    {
        return (currentSize / totalSize) * 100;
    }
    

提交回复
热议问题