从Azure Blob存储中检索pdf

时间:2019-05-05 15:17:11

标签: c# pdf azure-storage-blobs

我正在尝试从我的azure blob存储中检索pdf文档。我正在获取文档,但是当我尝试打开它时,它告诉我它无法读取数据。

[HttpGet("GetFromBlob")]
    public async Task<ActionResult> GetFileFromBlob(string id)
    {

        MemoryStream ms = new MemoryStream();

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connectionString");

        CloudBlobClient BlobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer c1 = BlobClient.GetContainerReference("blobName");

        if (await c1.ExistsAsync())
        {
            CloudBlob file = c1.GetBlobReference("FileReference");

            if (await file.ExistsAsync())
            {
                await file.DownloadToStreamAsync(ms);
                Stream blobStream = file.OpenReadAsync().Result;
                return File(blobStream, file.Properties.ContentType, file.Name);
            }
            else
            {
                return Content("File does not exist");
            }
        }
        else
        {
            return Content("Container does not exist");
        }
    }

结果是我的文件格式错误

1 个答案:

答案 0 :(得分:0)

请尝试使用下面的代码,该代码对我而言效果很好:

在代码块if(await file.ExistsAsync())中:

        if (await file.ExistsAsync())
        {
            await file.DownloadToStreamAsync(ms);
            var stream = await file.OpenReadAsync();
            return File(stream, "application/pdf");
        }
相关问题