user2195741
user2195741

Reputation:

How to display an image from a server side store in memory?

I have images saved in a server side folder. The server has the path of the images. The client cannot access that folder but the server can. I cannot attach the URL in the src attribute in an img tag because the browser will not be able to display as the client does not have permission.

How can I display those images in this case? I was told that the server can save the image in memory and then render those images in the client side - how can I do that? I'm using MVC 4, c# with sql server 2008 r2

Upvotes: 2

Views: 2820

Answers (3)

user2291492
user2291492

Reputation: 1

You need to link the images to point to a controller. The controller then needs to return a FileResult with the correct mimetype to the browser.

The sequence is as follows:

  1. Browser requests page
  2. Server return page with back link (e.g. <img src='/files/get/123.png'/>)
  3. Browser requests image in back link
  4. Server reads image from disk DB answering to controller (FilesController) action call (Get) with a FileResult return type. Remember to set the mime type to image\png or gif or jpeg based on your image format.
  5. Server returns image to brower

Upvotes: 0

takemyoxygen
takemyoxygen

Reputation: 4394

If you store images in a folder then you can use File() method with physical file path directly:

public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg");
    return base.File(path, "image/jpeg");
}

Upvotes: 1

Eric J.
Eric J.

Reputation: 150158

You can use the File overload that takes a path and a mime type. In your controller action:

// Sub the appropriate mime type for the image
return File(thePathFromTheDb, "image/jpg"); 

http://msdn.microsoft.com/en-us/library/dd492492(v=vs.108).aspx

Alternately if your image data were coming from the DB, in your controller action:

byte[] bytes = GetImageBytesFromDatabase();  // Sub your code to get bytes
return File(bytes, "image/jpg"); // Sub the appropriate mime type for the image

http://msdn.microsoft.com/en-us/library/dd460208(v=vs.108).aspx

Upvotes: 1

Related Questions