我需要使用 API 将 PDF 或 Excel 文件从 azure blob 存储传输到前端。我正在使用download to byte array of blob storage然后将其转换为内存流以将其发送回用户。
这是我的 Controller
[AllowAnonymous]
[HttpGet]
[Route("GetFiles")]
public HttpResponseMessage GetFiles()
{
const string StorageAccountName = "nameofAccount";
const string StorageAccountKey = "TheKey";
try
{
var storageAccount = new CloudStorageAccount(new StorageCredentials(StorageAccountName, StorageAccountKey), true);// login to azure and storage Account
var bloblClinet = storageAccount.CreateCloudBlobClient();// get blob client refernce
var container = bloblClinet.GetContainerReference("crmtestblob");// get container refernce
var blob = container.GetBlockBlobReference("test.xlsx");
long fileByteLength = blob.Properties.Length;// this return -1
byte[] fileContent = new byte[100000];
var MyArray = blob.DownloadToByteArray(fileContent, 0);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(MyArray);//application/octet-stream
result.Content = new StreamContent(stream);//application/vnd.ms-excel
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "test.xlsx"
};
return result;
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
我收到回复 200 但没有发送文件,或者文件已损坏 任何帮助都会很棒
最佳答案
您错误地使用了 DownloadToByteArray
函数导致了您的问题。
根据官方API引用CloudBlob.DownloadToByteArray(Byte\[\], Int32, AccessCondition, BlobRequestOptions, OperationContext) Method
,函数的返回结果是读入缓冲区的总字节数
,而不是blob内容。
下面有两个 SO 线程,我认为它们的答案足以帮助您修复它。
Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2
使用
CloudBlob.OpenReadAsync Method
打开一个可读流作为响应流内容。var stream = await blob.OpenReadAsync(); result.Content = new StreamContent(stream);
HttpResponseMessage Redirect to Private Azure Blob Storage
使用 sas token 将请求重定向到 blob url。
var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)//Assuming you want the link to expire after 1 hour }); var blobUrl = string.Format("{0}{1}", blob.Uri.AbsoluteUri, sasToken); var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = new Uri(bloburl);
关于c# - 使用 API 从 Azure blob 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57791482/