Reputation: 1197
In my Asp.net MVC I had used following code when the image file kept in an actual folder structure.
public FileResult DownloadFile(string imageName)
{
string fullPath = this.GetFullPath(imageName);
string contentType = " image/pjpeg";
return new FilePathResult(fullPath, contentType)
{
FileDownloadName = imageName
};
}
However now we have moved images to Azure Blob, And how can we download the image from there. Since FilePathResult dint work out we tried using the following code.
public ActionResult DownloadFile(string imgName)
{
string fullPath = imgName;
CloudStorageAccount account = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConString"));
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer blobContainer = client.GetContainerReference(ConfigurationManager.AppSettings["BlobReference"]);
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(imgName);
return Redirect(blockBlob.Uri.AbsoluteUri);
}
However the files are not downloading, instead it opens in a new window, Please guide me to download the file instead of opening in the new window.
Upvotes: 0
Views: 2858
Reputation: 136336
So there are two ways by which you can accomplish this thing:
1. Assuming you would always want the file to be downloaded
If you want the file to be always downloaded, you can set the Content-Disposition
property of the blob as attachment; filename=yourdesiredfilename
. In this case blockBlob.Uri.AbsoluteUri
will always force the file to download.
2. Assuming you want the flexibility of both downloading the file sometimes and opening the file in the browser
In this case, you could create a Shared Access Signature (SAS) on the blob and specify Content-Disposition
header as a part of SAS. Here's the sample code to do so:
CloudStorageAccount acc = new CloudStorageAccount(new StorageCredentials("<accountname>", "<accountKey>"), true);
var client = acc.CreateCloudBlobClient();
var container = client.GetContainerReference("<containername>");
var blob = container.GetBlockBlobReference("<imagename.png>");
var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
Permissions = SharedAccessBlobPermissions.Read
}, new SharedAccessBlobHeaders()
{
ContentDisposition = "attachment;filename=<imagename.png>",
});
var blobUrl = blob.Uri.AbsoluteUri + sasToken;
Redirect(blobUrl);
My recommendation would be to go with #2 as it gives you more security + you will be able to share blobs from private blob containers as well.
Upvotes: 1