正在将大文件上载到azure blob
本文关键字:azure blob 上载 文件 | 更新日期: 2023-09-27 18:20:41
我正在使用以下程序将大文件上传到azure blob存储。当上传一个小于500KB的小文件时,程序在其他情况下运行良好我在下面的行中得到一个错误:
blob.PutBlock(blockIdBase64,stream,null)
as"Microsoft.WindowsAzure.Storage.dll中发生了类型为"Microsoft.WindowsAzure.StorageException"的未处理异常附加信息:远程服务器返回错误:(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);
}
}
您得到这个错误是因为您的块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.