c# - 使用 API 从 Azure blob 下载

标签 c# azure api blob azure-blob-storage

我需要使用 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 线程,我认为它们的答案足以帮助您修复它。

  1. 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);
    
  2. 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/

相关文章:

javascript - C# 属性值不会在 Javascript/jquery 中被修改

azure - ARM模板: Resource Not Found Errors when grabbing outputs from Vault and Secrets

javascript - angularJS $http.get 与 API 通信

php - PayPal Rest API for Payments 在沙箱中返回 NULL

api - 未处理的异常:错误状态:无法设置内容类型为 “application/json”的请求的正文字段

c# - 在 .NET 4.6.1 上使用 SignalR Core

c# - 从 xsd 架构文件生成类时出错

c# - 确定哪个进程正在锁定剪贴板

azure - AKS - Terraform 的 network_profile block

IIS 共享配置覆盖 Azure 中 FTP 服务器的 IP 地址