5

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.

user2945722
  • 1,293
  • 1
  • 16
  • 35
  • Possible duplicate: http://stackoverflow.com/questions/20508788/do-i-need-content-type-application-octet-stream-for-file-download – adv12 Jun 19 '15 at 14:38
  • 1
    This comes down to what HTTP headers are set on the response. You want: `Content-Type: image/jpg` and `Content-Disposition: attachment; filename="picture.jpg"` – adv12 Jun 19 '15 at 14:39

2 Answers2

2

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(); // !!!  
andrew.fox
  • 7,435
  • 5
  • 52
  • 75
0

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");
}
Neil Thompson
  • 6,356
  • 2
  • 30
  • 53