上传文件到azure blob存储时没有进度信息

时间:2016-11-24 10:23:38

标签: azure azure-cloud-services azure-blob-storage

我在我的Android应用程序中使用azure blob存储来存储文件。 用于将文件从android手机上传到blob存储我正在使用" CloudBlockBlob"例 示例: - " cloudBlockBlob.uploadFromFile(File_Path,File_Uri)

问题: 1.我无法获得上传操作的上传进度。 2.如果由于某些网络问题无法获取报告而导致上传失败。 3.上传完成后没有确认报告。

请帮助我。

1 个答案:

答案 0 :(得分:1)

要更好地控制上传过程,您可以将文件拆分为更小的块,上传单个块,根据上传的块显示进度,并在所有块成功传输后立即提交上传。 您甚至可以同时上传多个块,在7天内暂停/恢复上传或重试失败的块上传。

这一方面是更多的编码,但另一方面更多的控制。

作为切入点,这里是C#中的一些示例代码,因为我不熟悉Android for Java:

CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(Path.GetFileName(fileName));

int blockSize = 256 * 1024; //256 kb

using (FileStream fileStream = 
  new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
  long fileSize = fileStream.Length;

  //block count is the number of blocks + 1 for the last one
  int blockCount = (int)((float)fileSize / (float)blockSize) + 1;

  //List of block ids; the blocks will be committed in the order of this list 
  List<string> blockIDs = new List<string>();

  //starting block number - 1
  int blockNumber = 0;

  try
  {
    int bytesRead = 0; //number of bytes read so far
    long bytesLeft = fileSize; //number of bytes left to read and upload

    //do until all of the bytes are uploaded
    while (bytesLeft > 0)
    {
      blockNumber++;
      int bytesToRead;
      if (bytesLeft >= blockSize)
      {
        //more than one block left, so put up another whole block
        bytesToRead = blockSize;
      }
      else
      {
        //less than one block left, read the rest of it
        bytesToRead = (int)bytesLeft;
      }

      //create a blockID from the block number, add it to the block ID list
      //the block ID is a base64 string
      string blockId = 
        Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",
          blockNumber.ToString("0000000"))));
      blockIDs.Add(blockId);
      //set up new buffer with the right size, and read that many bytes into it 
      byte[] bytes = new byte[bytesToRead];
      fileStream.Read(bytes, 0, bytesToRead);

      //calculate the MD5 hash of the byte array
      string blockHash = GetMD5HashFromStream(bytes);

      //upload the block, provide the hash so Azure can verify it
      blob.PutBlock(blockId, new MemoryStream(bytes), blockHash);

      //increment/decrement counters
      bytesRead += bytesToRead;
      bytesLeft -= bytesToRead;
    }

    //commit the blocks
    blob.PutBlockList(blockIDs);
  }
  catch (Exception ex)
  {
    System.Diagnostics.Debug.Print("Exception thrown = {0}", ex);
  }
}