8

This question has been asked before a while ago. I'm hoping the answer is different today.

I am using Azure blob storage to save images (jpg) for a web site. I am linking directly to the files in my <img> tags and that is working great (have enabled anonymous access). The problem is that if the user clicks on the image (which links directly to the file) they are forced to download it and can not view it in the browser.

Is there a way to set the headers for the blob storage to allow viewing it directly in the browser and not forcing a download.

Update 1:

Based on this How can I view an image from Azure Blob Storage, rather than download it? and this https://social.msdn.microsoft.com/Forums/windowsapps/en-US/b8759195-f490-420b-a587-2bb614366ad2/embedding-images-from-blob-storage-in-ssrs-report-does-not-work

I found that I am not setting the content type, which is causing the problem. I need to set it to "image/jpeg". Im not quite sure how to do that however. This is the code I am using to store the image.

using Microsoft.Azure.Storage.Blob

/// <summary>
/// Save a file to azure blob storage.
/// </summary>
/// <param name="name">Name of file</param>
/// <param name="file">filestream</param>
/// <param name="ct">Cancellationtoken</param>
public async Task<bool> SaveFile(Stream fileStream, string fileName, CancellationToken ct)
{
   CloudBlockBlob cloudBlockBlob = _blobContainer.GetBlockBlobReference(fileName);

   fileStream.Position = 0;
   await cloudBlockBlob.UploadFromStreamAsync(fileStream, ct);

   return true;
}

I have not found any type of ".Content", or "Type" property on this. Will keep digging.

Update 2: may have found the solution:

cloudBlockBlob.Properties.ContentType = "image/jpg";

Testing

Update 3: That did it. Using this to set proper content types for images and pdf and they are now viewable in the browser.

if (fileName.EndsWith(".jpg"))
{
    cloudBlockBlob.Properties.ContentType = "image/jpg";
}
else if (fileName.EndsWith(".pdf"))
{
    cloudBlockBlob.Properties.ContentType = "application/pdf";
}
JensB
  • 6,663
  • 2
  • 55
  • 94
  • Use javascript onclick() event on the `img` to navigate to a page in your application that shows the image? – David Browne - Microsoft Aug 15 '20 at 20:28
  • I could do that but I would just much rather link directly to the image so that people on mobile browsers can view it better without it being surrounded by any type of html. I personally dont like when web sites pop a just slightly larger version of an image when you click it instead of the raw file. – JensB Aug 15 '20 at 20:30

1 Answers1

6

See question for details. But setting content type can be done with:

cloudBlockBlob.Properties.ContentType = "image/jpg";
JensB
  • 6,663
  • 2
  • 55
  • 94