我创建了一个支持从手机上传一个或多个文件的 Windows Phone 8.1 (WinRT) 应用程序。
我为此使用后台上传器。我使用以下功能创建后台上传
public async void AddUploads(IReadOnlyList<StorageFile> uploadFiles)
{
BackgroundTransferGroup group = BackgroundTransferGroup.CreateGroup(this.GroupId);
group.TransferBehavior = BackgroundTransferBehavior.Serialized;
// BackgroundUploader automatically sets Content-Type header to multipart/related
BackgroundUploader uploader = new BackgroundUploader();
uploader.TransferGroup = group;
uploader.SetRequestHeader("Authorization", "Bearer " + this.AccessToken);
uploader.Method = "POST";
foreach (StorageFile file in uploadFiles)
{
UploadOperation upload = await uploader.CreateUploadAsync(new Uri(this.uploadUri, UriKind.Absolute), GetTransferContents(file), "related");
Progress<UploadOperation> progressCallback = new Progress<UploadOperation>(UploadProgressNotification);
// Will this exception be caught??
try
{
upload.StartAsync().AsTask(this.CancelToken, progressCallback);
}
}
}
我通过以下回调更新 UI 以获取进度
public void UploadProgressNotification(UploadOperation upload)
{
var ignore = Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
var uploadProgress = upload.Progress;
Progress = (uploadProgress.BytesSent + uploadProgress.BytesReceived) * 100.0 / (uploadProgress.TotalBytesToSend + uploadProgress.TotalBytesToReceive);
switch(uploadProgress.Status)
{
case BackgroundTransferStatus.Canceled:
Status = "Canceled";
break;
case BackgroundTransferStatus.Idle:
Status = "Waiting";
break;
case BackgroundTransferStatus.PausedNoNetwork:
Status = "Waiting for network";
break;
case BackgroundTransferStatus.Running:
Status = "Uploading";
break;
case BackgroundTransferStatus.Error:
Status = "Failed";
System.Diagnostics.Debug.WriteLine(upload.GetResponseInformation().StatusCode);
var headers = upload.GetResponseInformation().Headers;
foreach(string key in headers.Keys)
{
System.Diagnostics.Debug.WriteLine(headers[key]);
}
System.Diagnostics.Debug.WriteLine(upload.GetResponseInformation().IsResumable);
break;
case BackgroundTransferStatus.Completed:
Status = "Completed";
break;
default:
Status = "Waiting";
break;
}
UploadStatus = uploadProgress.Status;
});
}
但是,大多数情况下,即使文件成功上传到服务器并且进度为 100%,UploadOperation 的状态也不会从“正在运行”变为“已完成”。当我上传多个文件时,其中一些显示“已完成”状态,而另一些显示“正在运行”,但所有文件都已成功上传。
如何确定文件何时完全上传?