最新内容优先发布于个人博客:小虎技术分享站,随后逐步搬运到博客园。
创作不易,如果觉得有用请在 Github 上为博主点亮一颗小星星吧!
前两天,我分享了一个用于简单上传文件到S3的小工具。在知乎上看到了一个问题,询问如何实现显示MINIO上传进度。因此,我对这个小工具进行了拓展,使其能够在上传大文件时显示进度。
完整代码托管于Github:mrchipset/simple-wpf
实现上传进度显示的方式如下:
具体的实现代码如下:
private async Task<bool> UploadLargeFileAsync()
{
var credentials = new BasicAWSCredentials(_accessKey, _secretKey);
var clientConfig = new AmazonS3Config
{
ForcePathStyle = true,
ServiceURL = _endpoint,
};
bool ret = true;
using (var client = new AmazonS3Client(credentials, clientConfig))
{
try
{
var fileTransferUtility = new TransferUtility(client);
var uploadRequest = new TransferUtilityUploadRequest
{
BucketName = LargeBucket,
FilePath = UploadLargeFile,
Key = System.IO.Path.GetFileName(UploadLargeFile)
};
uploadRequest.UploadProgressEvent += UploadRequest_UploadProgressEvent;
await fileTransferUtility.UploadAsync(uploadRequest);
}
catch (FileNotFoundException e)
{
ret = false;
this.Dispatcher.Invoke(new Action(() => this.statusLargeTxtBlk.Text = e.Message));
}
catch (AmazonS3Exception e)
{
ret = false;
if (e.ErrorCode != null &&
(e.ErrorCode.Equals("InvalidAccessKeyId") ||
e.ErrorCode.Equals("InvalidSecurity")))
{
this.Dispatcher.Invoke(new Action(() => this.statusLargeTxtBlk.Text = "Please check the provided AWS Credentials"));
}
else
{
this.Dispatcher.Invoke(new Action(() => this.statusLargeTxtBlk.Text = $"An error occurred with the message '{e.Message}' when writing an object"));
}
}
catch(Exception e)
{
this.Dispatcher.Invoke(new Action(() => this.statusLargeTxtBlk.Text = $"An error occurred with the message '{e.Message}' when writing an object"));
}
}
return ret;
}
private void UploadRequest_UploadProgressEvent(object? sender, UploadProgressArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
this.uploadProgress.Value = e.TransferredBytes * 100 / e.TotalBytes ;
}));
}
值得一提的是,在上传进度的事件处理函数中,由于我们通过异步方法执行上传函数,因此我们需要使用Dispatcher来更新数据到UI上。
https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html
https://www.xtigerkin.com/archives/96/