我正在尝试从内存流中的 azure blob 存储下载 pdf 文件。但是,当我尝试打开该文件时,它没有加载。
这是我正在使用的代码。 下载代码
protected void blobDownload_Click(object sender, EventArgs e)
{
//Getting the blob storage container values
DBAccess dbaCon = new DBAccess();
DataTable dt = dbaCon.GetTrainingRecord(TrainingTrainingRecordID.Value);
string companyID = dt.Rows[0].Field<string>("fk_company_id");
string blobStorageName = dt.Rows[0].Field<string>("uploaded_file");
string filename = dt.Rows[0].Field<string>("display_file_name");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(System.Text.RegularExpressions.Regex.Replace(companyID.ToLower(), @"\s+", ""));
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobStorageName);
MemoryStream memStream = new MemoryStream();
blockBlob.DownloadToStream(memStream);
blockBlob.FetchAttributes();
HttpResponse response = HttpContext.Current.Response;
//response.ContentType = blockBlob.Properties.ContentType;
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "Attachment; filename=" + filename);
response.AddHeader("Content-Length", blockBlob.Properties.Length.ToString());
response.BinaryWrite(memStream.ToArray());
}
基本上,上面的代码是通过单击按钮触发的,通过浏览器下载文件,但在尝试打开该文件时无法加载。我已经 checkin 了azure门户,我可以通过azure门户直接下载该文件,并且文件没问题。
我尝试直接设置内容类型,但这似乎不起作用。
Pdf 文件似乎是我用 .jpg 和 .png 文件测试过的唯一不起作用的文件,它可以正常下载和打开。
谢谢
更新
该问题已基本得到解决,因为这是我上传文件的方式的问题。由于我需要唯一地存储文件,因此我必须更改 Blob 存储中的名称来克服这个问题,因此我使用了下面的 .SaveAs()
函数。
上传代码
private void uploadFile(string blobContainer, string randomFileName)
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
// Create the container if it doesn't already exist.
container.CreateIfNotExists();
// Retrieve reference to a blob named "randomFileName".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(randomFileName);
filMyFile.PostedFile.SaveAs(Server.MapPath("~/") + randomFileName);
// Create or overwrite the "myblob" blob with contents from a local file.
using (filMyFile.PostedFile.InputStream)
{
blockBlob.UploadFromStream(filMyFile.PostedFile.InputStream);
}
}
该文件在 Edge 和 Chrome 中下载良好,但在 Firefox 中名称会缩短并且文件扩展名丢失。以下是显示该问题的屏幕截图。
最佳答案
根据我的测试,你的代码在我这边工作正常。 PDF 应该与其他 blob 没有区别。由于 azure blob 存储上没有文件类型,因此它只是一个 blob 名称。扩展类型对于操作系统是已知的。
我建议您下载名为 xxx.pdf 的文件。一般我们还需要PDF阅读器来阅读pdf文件。如果安装了Microsoft Edge浏览器,您可以直接打开.pdf文件。
更新:
对于 Firefox,可以将其配置为直接保存文件,然后它应该可以工作。
关于c# - 重新打开时从 azure 下载 PDF 时无法加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798704/