Sergio
Sergio

Reputation: 9917

asp.net mvc: How to share images file across domains

I am in a situation whereby I have two sites, one a sub-domain of the other. One site uploads images to a folder and saves a reference to the image to a database, which is accessible by the other site.

What I need to be able to do is to access the images in both sites.

I have considered saving the files in a folder that is accessible by both sites, outside of the public html folders, but am then not sure how to reference these images without having nasty src attributes that show full server paths.

Thanks

Upvotes: 0

Views: 905

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could write a controller action that will serve them:

public ActionResult Image(int id)
{
    var image = ... go and fetch the image information from the database (you will need the path to the image on the server and the content type)
    string path = image.Path; // could be any absolute path anywhere on your server, for example c:\foo\bar.jpg
    string contentType = image.ContentType; // for example image/jpg
    return File(path, contentType);
}

and then in your views:

<img src="@Url.Action("Image", "SomeController", new { id = 123 })" alt="" />

which will be rendered as:

<img src="/SomeController/Image/123" alt="" />

where 123 will obviously be the unique identifier of the image record in your database.

Also make sure that you have granted the necessary permissions to the account that your application runs under in IIS to the folder in which you are storing your images otherwise it won't be able to read them if this folder is outside of the application root.

Upvotes: 3

Related Questions