simbada simbada - 1 year ago 103
AngularJS Question

how to return image url instead of file path

I am facing an issue when showing uploaded image in browser.
I get error

Not allowed to load local resource:

I wrote the following line of code to store image on server under App_data.

File.Path = Url.Content(string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Images"), fileName));

File path saved in DB as following



<img ng-src="{{motor.FileUploads[0].Path}} alt="Description" />

After googling i got the reason for this error.

Basically i need to return back Image URL instead of file path.

I am not sure how i can return image path back to angular client.

Can someone guide me on it.

Answer Source

You don't need to specify the complete physical path, when reference from the browser

File.Path = Url.Content(string.Format("~/App_Data/Images/{0}", fileName));

this should return the relative URL

Update : well this won't work since you can directly access contents of the app_data folder. you can approach this either of these ways

  • move the images out of the app_data folder to like ~/images folder and it should work or
  • keep the file in the app_data folder but stream the file using content/file result action on one of your controllers

bare minimum sample implementation of the second option would look like

public class UploadsController : Controller
    public ActionResult Image( string fileName )
        //!validate file name!
        return File( Server.MapPath( $"~/App_Data/{fileName}" ), "image/jpeg" );

then in the HTML it can be referenced as <img src="api/uploads/image?filename=temp.jpg" ...