将大文件上传到azure blob

时间:2015-11-05 10:00:58

标签: c# .net azure c#-4.0 azure-storage-blobs

我正在使用以下程序将大文件上传到azure blob存储。 上传小于500KB的小文件时,程序工作正常 我在以下行中收到错误:

blob.PutBlock(blockIdBase64,stream,null);
as" 未处理的类型' Microsoft.WindowsAzure.Storage.StorageException'发生在Microsoft.WindowsAzure.Storage.dll中 附加信息:远程服务器返回错误:(400)错误请求。"

没有关于例外的细节,所以我不确定这个问题是什么。关于以下程序中可能出现的错误,是否有任何建议:

class Program
    {

    static void Main(string[] args)
    {
    string accountName = "newstg";
    string accountKey = "fFB86xx5jbCj1A3dC41HtuIZwvDwLnXg==";
    // list of all uploaded block ids. need for commiting them at the end
    var blockIdList = new List<string>();
    StorageCredentials creds = new StorageCredentials(accountName, accountKey);
    CloudStorageAccount storageAccount = new CloudStorageAccount(creds, useHttps: true);
    CloudBlobClient client = storageAccount.CreateCloudBlobClient();
     
     
    CloudBlobContainer sampleContainer = client.GetContainerReference("newcontainer2");
    string fileName = @"C:\sample.pptx";
    CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("APictureFile6");

    using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
    int blockSize = 1;
    // block counter
    var blockId = 0;
    // open file
    while (file.Position < file.Length)
    {
    // calculate buffer size (blockSize in KB) 
    var bufferSize = blockSize * 1024 < file.Length - file.Position ? blockSize * 1024 : file.Length - file.Position;
    var buffer = new byte[bufferSize];
    // read data to buffer
    file.Read(buffer, 0, buffer.Length);
    // save data to memory stream and put to storage
    using (var stream = new MemoryStream(buffer))
    {
    // set stream position to start
    stream.Position = 0;
    // convert block id to Base64 Encoded string 
    var blockIdBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockId.ToString(CultureInfo.InvariantCulture)));
    blob.PutBlock(blockIdBase64, stream, null);
    blockIdList.Add(blockIdBase64);
    // increase block id
    blockId++;
    }
    }
    file.Close();
    }
    blob.PutBlockList(blockIdList);
    }
    }

1 个答案:

答案 0 :(得分:5)

您收到此错误是因为您的块ID长度不同。因此,对于前9个块,您的块ID长度为1个字符,但是一旦到达第10个块,您的块ID长度就变为2.请执行以下操作:

var blockIdBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockId.ToString("d6", CultureInfo.InvariantCulture)));

这样所有的块ID都是6个字符长。

有关详情,请参阅此处的URI Parameters部分:https://msdn.microsoft.com/en-us/library/azure/dd135726.aspx