【问题标题】:Downloading file from Azure does not download full file, same works fine in local从 Azure 下载文件不会下载完整文件,在本地也可以正常工作
【发布时间】:2019-09-20 17:28:49
【问题描述】:

我们使用 Azure 来存储我们的文件,当我们上传/下载文件时,它使用 Azure 模拟器,一切正常并下载完整大小的文件。

但我们发现,当我们尝试在使用 Azure 的舞台环境中下载文件时,文件未完全下载。

下载代码如下:

CloudBlobContainer blobContainer = await GetContainerAsync(tenantId);
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileId);

            return await blockBlob.DownloadRangeToByteArrayAsync(target, index, offset, length);

我们从 API 做以下事情:

var read = await _fileStorageService.DownloadRangeToByteArrayAsync(id, buffer, 0, offset, dataToRead > bufferSize ? bufferSize : dataToRead);
                            offset += read;
                            dataToRead -= read;

                            await Response.Body.WriteAsync(buffer, 0, read);
                            await Response.Body.FlushAsync();

我们在这里做错了什么?提前致谢

【问题讨论】:

    标签: c# azure asp.net-web-api


    【解决方案1】:

    我认为您将错误的长度传递给方法,并且它仅将文件下载到该长度。如果你想下载整个文件,你应该这样做:

    CloudBlobContainer blobContainer = await GetContainerAsync(tenantId);
    CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileId);
    return await blockBlob.DownloadToByteArrayAsync(target, 0);
    

    【讨论】:

    • 谢谢,但我们正在分块读取,因为文件可能很大。我的意思不是一次下载整个文件,我的意思是它根本不下载整个文件,在本地工作正常。
    【解决方案2】:

    试试这样。您需要在 blob 上执行 FetchAttributesAsync 以获取字节数组的初始大小。如果您想分块下载,只需使用不同的索引进行多次DownloadToByteArrayAsync 调用。

     public async Task<byte[]> GetFile(string container, string directory, string blobName)
                 {
                     CloudBlobContainer cloudContainer = client.GetContainerReference(container);
                     CloudBlobDirectory cloudDirectory = cloudContainer.GetDirectoryReference(directory);
                     CloudBlockBlob blob = cloudDirectory.GetBlockBlobReference(blobName);
    
                     await blob.FetchAttributesAsync();
                     long fileByteLength = blob.Properties.Length;
                     byte[] fileContent = new byte[fileByteLength];
                     for (int i = 0; i < fileByteLength; i++)
                     {
                         fileContent[i] = 0x20;
                     }
                     await blob.DownloadToByteArrayAsync(fileContent, 0);
                     return fileContent;
                 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多