2

I store my image files in my App_Data/img folder and store the name of each image file in my database table. I access the DB through Entity Framework. My initial idea was getting the name of image file from DB, creating an image path string and then assigning that string to the "src" attribute of an element. But it just didn't work. Nothing displayed. I have gone through various suggestions but none worked for me. The following was the most refined one but it did'nt work either

<img src="~/App_Data/img/@Url.Content(Model.ImagePath)" height=100 width=200 />

Here, it seems that tilde doesn't work. Becasue in the page source, my path is rendered as written not as a relative path to the root folder of my app.

1) How can I solve that path issue? Why does not tilde help me to point to my root folder?

2) Is that a good way to implement such a task? As far as I searched, many people address base64 string stuff. With a static / predefined file path, base64 conversion worked for me as well. But I could'nt manage to work with base64 stuff when I dynamically change the file to be shown. Therefore, I gave up using it. However, I'm not sure that if that's a good idea?

EmreYZ
  • 49
  • 1
  • 9
  • What value you have in the `Model.ImagePath` expression ? – Shyju Dec 12 '17 at 18:32
  • 2
    You can't serve your images directly from the `App_Data` folder. – DavidG Dec 12 '17 at 18:32
  • App_Data is a special directory in ASP.NET, which is supposed to store data files like XML files / mdf files to store data. It has restricted access as well. Why not use another directory ? – Shyju Dec 12 '17 at 18:34
  • If you want to serve the images from App_Data folder you need a controller (maybe ImageController is a good name for it) which will read the content from that path – Sir Rufo Dec 12 '17 at 18:48

3 Answers3

1

The App_Data folder is a special folder and you can't serve your images directly from there. Move them to another folder, for example /images, and it will work (providing you supply the correct path of course.)

DavidG
  • 113,891
  • 12
  • 217
  • 223
1
  1. URL.Content(path) is used to resolve tilde expressions as per MVC @Url.Content vs @Url.Action.

  2. It's not a good way. App_Data files cannot be served by ASP.NET: https://stackoverflow.com/a/528872/4378740

Assuming Model.ImagePath is something like "cute_dog.png", a better way is to create an images folder in the root directory. Then you can use something like:

<img src="/images/@(Model.ImagePath)" height=100 width=200 />
chakeda
  • 1,551
  • 1
  • 18
  • 40
0

Are you saving image name with extension (MIME Type) included? Can you browse source when page will open and find src attribute value of img tag? It should be followed by correct extension.

Why dont you use just Model.ImagePath like:

src="/app_data/img/@Model.ImagePath"

Kopadze
  • 31
  • 4