我正在尝试从内存流中的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());
}
基本上上面的代码是在点击按钮时触发的,文件是通过浏览器下载的,但是当试图打开文件时无法加载。我已经检查了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);
}
}