【发布时间】:2022-12-24 11:59:48
【问题描述】:
我正在使用 NuGet 包Azure.Storage.Blobs v.12.14.1从 Azure 存储下载文件,然后将文件上传到 OneDrive。
这是我正在使用的代码:
var blobClient = new BlobClient({connection_string}, {container}, {file_path});
var blobSize = blobClient.GetProperties().Value.ContentLength;
var client = _clientFactory.CreateClient();
long blockSize = (10 * 1024 * 1024);
blockSize = Math.Min(blobSize, blockSize);
long currentPointer = 0;
long bytesRemaining = blobSize;
do
{
var bytesToFetch = Math.Min(blockSize, bytesRemaining);
await using (var blobStream = await blobClient.OpenReadAsync(currentPointer, (int)bytesToFetch, null, cancellationToken))
{
blobStream.Position = 0;
var fileContent = new StreamContent(blobStream);
fileContent.Headers.ContentLength = bytesToFetch;
fileContent.Headers.ContentRange = new ContentRangeHeaderValue(currentPointer, currentPointer + bytesToFetch - 1, blobSize);
var res = await client.PutAsync(fileConsentCardResponse.UploadInfo.UploadUrl, fileContent, cancellationToken);
currentPointer += bytesToFetch;
bytesRemaining -= bytesToFetch;
}
}
while (bytesRemaining > 0);
当文件小于 blockSize: 10MB 时,这工作正常。代码执行后可以在OneDrive中看到该文件。
但是,当文件大于 blockSize 时,这将不再有效。不会引发任何错误,但在 OneDrive 中找不到该文件。
请帮忙,谢谢!!
更新:
我做了这个工作:
var blobClient = new BlobClient({connection_string}, {container}, {file_path});
var blobSize = blobClient.GetProperties().Value.ContentLength;
var client = _clientFactory.CreateClient();
long blockSize = (10 * 1024 * 1024);
blockSize = Math.Min(blobSize, blockSize);
long currentPointer = 0;
long bytesRemaining = blobSize;
do
{
var bytesToFetch = Math.Min(blockSize, bytesRemaining);
HttpRange range = new HttpRange(currentPointer, bytesToFetch);
var blobStreamResult = await blobClient.DownloadStreamingAsync(
new BlobDownloadOptions { Range = range });
using (MemoryStream ms = new MemoryStream())
{
blobStreamResult.Value.Content.CopyTo(ms);
ms.Position = 0;
var fileContent = new StreamContent(ms);
fileContent.Headers.ContentLength = bytesToFetch;
fileContent.Headers.ContentRange = new ContentRangeHeaderValue(currentPointer, currentPointer + bytesToFetch - 1, blobSize);
var res = await client.PutAsync(fileConsentCardResponse.UploadInfo.UploadUrl, fileContent, cancellationToken);
}
currentPointer += bytesToFetch;
bytesRemaining -= bytesToFetch;
}
while (bytesRemaining > 0);
还有一个问题,如果文件很大(比如1GB),它会消耗太多内存,如何解决这个问题?谢谢!
【问题讨论】:
标签: .net download upload azure-blob-storage azure-storage