如何在Windows应用商店中将数据上传到azure blob时显示进度条

时间:2016-02-28 09:14:57

标签: azure windows-store-apps bytearray memorystream windows-8.1-universal

我已按照以下帖子以块的形式上传到blob

How to track progress of async file upload to azure storage

但是这不适用于Windows应用商店应用程序或Windows 8.1应用程序,因为在win 8.1应用程序中不支持MemoryStream。

无论如何,我已修改上述主题中的代码并提出类似以下内容的内容

        CloudBlobClient myBlobClient = storageAccount.CreateCloudBlobClient();
        var filePicker = new FileOpenPicker();

        filePicker.FileTypeFilter.Add("*");
        var file = await filePicker.PickSingleFileAsync();
        string output = string.Empty;

            var fileName = file.Name;


        myBlobClient.SingleBlobUploadThresholdInBytes = 1024 * 1024;
        CloudBlobContainer container = myBlobClient.GetContainerReference("files");
        //container.CreateIfNotExists();
        CloudBlockBlob myBlob = container.GetBlockBlobReference(fileName);
        var blockSize = 256 * 1024;
        myBlob.StreamWriteSizeInBytes = blockSize;

        var fileProp = await file.GetBasicPropertiesAsync();
        var bytesToUpload = fileProp.Size;
        var fileSize = bytesToUpload;



        if (bytesToUpload < Convert.ToUInt64(blockSize))
        {
            CancellationToken ca = new CancellationToken();
            var ado = myBlob.UploadFromFileAsync(file).AsTask();
            await
                            //Console.WriteLine(ado.Status); //Does Not Help Much
                            ado.ContinueWith(t =>
                            {
                                //Console.WriteLine("Status = " + t.Status);
                                //Console.WriteLine("It is over"); //this is working OK
                            });
        }
        else
        {
            List<string> blockIds = new List<string>();
            int index = 1;
            ulong startPosition = 0;
            ulong bytesUploaded = 0;
            do
            {
                var bytesToRead = Math.Min(Convert.ToUInt64(blockSize), bytesToUpload);
                var blobContents = new byte[bytesToRead];




                using (Stream fs = await file.OpenStreamForWriteAsync())
                {
                    fs.Position = Convert.ToInt64(startPosition);
                    fs.Read(blobContents, 0, (int)bytesToRead);
                    //var iStream = fs.AsInputStream();



                    ManualResetEvent mre = new ManualResetEvent(false);
                    var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("d6")));
                    //Console.WriteLine("Now uploading block # " + index.ToString("d6"));
                    blockIds.Add(blockId);
                    var ado = myBlob.PutBlockAsync(blockId, fs.AsRandomAccessStream(), null).AsTask();
                    await ado.ContinueWith(t =>
                              {
                                  bytesUploaded += bytesToRead;
                                  bytesToUpload -= bytesToRead;
                                  startPosition += bytesToRead;
                                  index++;
                                  double percentComplete = (double)bytesUploaded / (double)fileSize;
                                  output += (percentComplete * 100).ToString() + ",";
                        // AppModel.TasksFormObj.SetProgress(percentComplete * 100);
                        // Console.WriteLine("Percent complete = " + percentComplete.ToString("P"));
                        mre.Set();
                              });

                mre.WaitOne();
                }
            }
            while (bytesToUpload > 0);
            //Console.WriteLine("Now committing block list");
            var pbl = myBlob.PutBlockListAsync(blockIds).AsTask();
             pbl.ContinueWith(t =>
            {
                //Console.WriteLine("Blob uploaded completely.");
            });
        }
    }

上面的代码会将文件保存在blob中并且进度也很好但是blob中保存的文件总是以0字节为单位。调试后我发现在var ado = myBlob.PutBlockAsync(blockId,fs.AsRandomAccessStream(),null)之后抛出了一个错误.AsTask();最后一次blob转移为

<?xml version="1.0" encoding="utf-16"?>
<!--An exception has occurred. For more information please deserialize this message via RequestResult.TranslateFromExceptionMessage.-->
<RequestResult>
  <HTTPStatusCode>400</HTTPStatusCode>
  <HttpStatusMessage>The value for one of the HTTP headers is not in the correct format.</HttpStatusMessage>
  <TargetLocation>Primary</TargetLocation>
  <ServiceRequestID>13633308-0001-0031-060b-7249ea000000</ServiceRequestID>
  <ContentMd5 />
  <Etag />
  <RequestDate>Sun, 28 Feb 2016 10:31:44 GMT</RequestDate>
  <StartTime>Sun, 28 Feb 2016 09:31:43 GMT</StartTime>
  <EndTime>Sun, 28 Feb 2016 09:31:44 GMT</EndTime>
  <Error>
    <Code>InvalidHeaderValue</Code>
    <Message>The value for one of the HTTP headers is not in the correct format.
RequestId:13633308-0001-0031-060b-7249ea000000
Time:2016-02-28T09:34:18.3545085Z</Message>
    <HeaderName>Content-Length</HeaderName>
    <HeaderValue>0</HeaderValue>
  </Error>
  <ExceptionInfo>
    <Type>StorageException</Type>
    <HResult>-2147467259</HResult>
    <Message>The value for one of the HTTP headers is not in the correct format.</Message>
    <Source>Microsoft.WindowsAzure.Storage</Source>
    <StackTrace>   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.&lt;ExecuteAsyncInternal&gt;d__c`1.MoveNext()</StackTrace>
  </ExceptionInfo>
</RequestResult>

然后在最后一次提交时,myBlob.PutBlockListAsync(blockIds)之后抛出的错误为指定的阻止列表无效

所以请有人帮助我弄清楚我做错了什么,或者让它100%工作的可行解决方案。

1 个答案:

答案 0 :(得分:0)

像这样使用AsTask()

 CancellationTokenSource _cts;

 _cts = new CancellationTokenSource();//<--In Constructor 

 var progress = new Progress<double>(TranscodeProgress); 
 await var ado = myBlob.UploadFromFileAsync(file).AsTask(_cts.Token, progress);