Azure blob storage download file instead of opening in the browser

5.8k Views Asked by At

I am uploading files to Azure blob storage using this code, where container is my CloudBlobContainer

    public void SaveFile(string blobPath, Stream stream)
    {
        stream.Seek(0, SeekOrigin.Begin);
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(virtualPath);

        blockBlob.Properties.ContentDisposition = 
"attachment; filename=" + Path.GetFileName(virtualPath);

        blockBlob.UploadFromStream(stream);
    }

Then when a user clicks on a file in my web page I am trying to trigger a download where they are prompted to either save/open the file. I do this by calling an Action which returns a redirect to the blob URL.

    public ActionResult LoadFile(string path)
    {    
        string url = StorageManager.GetBlobUrlFromName(path);
        return Redirect(url);
    }

The issue is this will open the files in the browser e.g. the user will be redirect away from my site and shown a .jpg file in the browser when I was expecting them to stay on my page but start downloading the file.

2

There are 2 best solutions below

0
On

One way to achieve what you want is for an MVC action to fetch the image from blob storage and return the File, ie:

public ActionResult LoadFile(string path)
{    
    byteArray imageBytes = ....get img from blob storage
    return File(byteArray, "image/png", "filename.ext");
}
0
On

What you possibly miss is invoking blockBlob.SetProperties() after setting properties.

On my code it looks like this:

blob.CreateOrReplace();
blob.Properties.ContentType = "text/plain";
blob.Properties.ContentDisposition = "attachment; filename=" + Path.GetFileName(blobName);
blob.SetProperties(); // !!!