C# 使用API从Azure blob下载
我需要使用API将PDF或excel文件从azure blob存储管道传输到前端。我正在使用,然后将其转换为内存流,将其发送回用户 这是我的控制器C# 使用API从Azure blob下载,c#,azure,api,blob,azure-blob-storage,C#,Azure,Api,Blob,Azure Blob Storage,我需要使用API将PDF或excel文件从azure blob存储管道传输到前端。我正在使用,然后将其转换为内存流,将其发送回用户 这是我的控制器 [AllowAnonymous] [HttpGet] [Route("GetFiles")] public HttpResponseMessage GetFiles() { const string StorageAccountName = "nameofAccount"; co
[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参考,函数的返回结果是读入缓冲区的字节总数,而不是blob内容
下面有两个这样的线程,我认为它们的答案对您修复它很有帮助
var stream = await blob.OpenReadAsync();
result.Content = new StreamContent(stream);
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);
我需要从azure存储下载一个文件。