使用API​​从Azure Blob下载

时间:2019-09-04 15:22:32

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

我需要使用API​​通过流水线将PDF或excel文件从天蓝色blob存储传递到前端。我正在使用download to byte array of blob storage,然后将其转换为内存流以将其发送回用户。

这是我的控制器

[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 但没有发送文件,或者文件已损坏 任何帮助都很好

1 个答案:

答案 0 :(得分:1)

您不正确地使用函数DownloadToByteArray导致了问题。

根据官方API参考CloudBlob.DownloadToByteArray(Byte\[\], Int32, AccessCondition, BlobRequestOptions, OperationContext) Method,该函数的返回结果为 The total number of bytes read into the buffer ,而不是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令牌将请求重定向到Blob网址。

    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);