locked
Asp.Net Core Image Get From Database RRS feed

  • Question

  • User197255166 posted

    Hi,

    I am using .NET Core. I created image folder. and added database. But I wanna show image in table. I have another setting. Can anyone help me ?

    Controller 

    TProjects proje = new TProjects();
                   if (resimyolu != null)
                   {
                       proje.CatId = catid;
                       proje.Baslik = baslik;
                       proje.İcerik = icerik;
                       var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot/resimler", resimyolu.FileName);
                       var stream = new FileStream(path, FileMode.Create);
                       proje.ResimYolu = resimyolu.FileName;
     
                   }
     
                   port.TProjects.Add(proje);
                   port.SaveChanges();

    Index.cshtml

    @foreach (var item in Model)
                                      {
                                          <tbody>
                                              <tr class="odd gradeX">
                                                  <td>@item.Id</td>
                                                  <td>@item.Baslik</td>
                                                  <td>@item.İcerik</td>
                                                  <td><img src="~/resimler/@item.ResimYolu" width="150" height="150" /></td>
     
                                                  <td>
                                                      <button class="btn btn-primary" data-toggle="modal" data-target=".@item.Id">
                                                          Düzenle
                                                      </button>
                                                  </td>
                                              </tr>
     
                                          </tbody>
                                      }

    Saturday, September 28, 2019 12:20 PM

All replies

  • User475983607 posted

    There's not enough detail to understand the problem you are trying to solve.  It look like you have multiple approaches for rendering an image. 

    I created a sample that illustrates how to populate an img tag using openly published standards that you can find in any beginning level tutorial.

            [HttpGet]
            public IActionResult ImageDemo()
            {
                //Mock image path result set
                List<string> images = new List<string>() { @"/img/switch.png", @"/img/switch.png" };
                return View(images);
            }
    @model List<string>
    
    @{
        ViewData["Title"] = "ImageDemo";
    }
    
    <h1>ImageDemo</h1>
    <div>
        @foreach(string s in Model)
        {
            <img src="@s" />
        }
    </div>

    Saturday, September 28, 2019 1:27 PM
  • User197255166 posted

    Hi,

    I shared the code above.

    Here, when saving, I add the images in the images folder in wwwroot and keep the name of the image in the database.

    Then I do not want to show the picture on the page.

    This was happening when using mvc. But .net core also has a different setting.

    Saturday, September 28, 2019 1:44 PM
  • User475983607 posted

    I shared the code above.

    Like many of your posts, you do not share enough detail for the community to debug your code.  We need, at least, the file path.    That's why I provided a very basic demo that illustrates how to populate a relative path to an "img" folder in the application root.  The example works in MVC and Core.

    But .net core also has a different setting.

    Not clear.

    Saturday, September 28, 2019 2:02 PM
  • User197255166 posted

    Hi,

    I shared debug code. can you click Image you can see my debug code.

    İmage

    And do you understand my problem?

    Saturday, September 28, 2019 2:37 PM
  • User475983607 posted

    And do you understand my problem?

    I do not understand the problem and I cannot reproduce this issue.  I suspect the image is not located in the expected folder.  For the thrid time, have you tried simply opening dev tools and looking at the image path?  Have you verified the image path exists in the image path found in the HTML?

    Seeing the debug screen makes the problem even more confusing,  I'm guessing you are using some 3rd party library that you have not told us about. 

    Saturday, September 28, 2019 3:11 PM
  • User197255166 posted

    Hi,

    I shared project view with visual studio. You can see and What am I doing wrong

    Database schema

    Saturday, September 28, 2019 3:19 PM
  • User409696431 posted

    "Then I do not want to show the picture on the page."

    I assume you meant you DO want to show the image.

    If the image doesn't show in the table, look at the page source with developer tools and see what the image source path is.  Is @item.ResimYolu being passed to your page?

    <img src="~/resimler/@item.ResimYolu" width="150" height="150" />
    Saturday, September 28, 2019 7:39 PM
  • User475983607 posted

    Did you enable the static fie handler in the startup.cs file?  Have you tried view the HTML in the browser's dev tools?  Have you tried opening the file from your browser's address bar?  Are you using a 3rd party library?

    I can't reproduce this error.  I'm guessing you are doing something that you are not telling us.

    Saturday, September 28, 2019 8:18 PM
  • User711641945 posted

    Hi Aliyilmaz,

    Could you share more detailed code that could reproduce your issue?

    If your image has been uploaded to wwwroot/resimler folder,you could use the following code to show the image:

    <img src="@Url.Content("~/resimler/" + @item.ResimYolu)" />

    And your Configure method in Startup.cs should be like below:

    app.UseRequestLocalization(options);
    app.UseStaticFiles();
    app.UseCookiePolicy();
    
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    Best Regards,

    Rena

    Monday, September 30, 2019 5:24 AM
  • User197255166 posted

    Hi,

    My startup.cs code like below. But still I dont get image. I try like this.

      @foreach (var items in ViewBag.Proje)
                            {
                                <div id="catid" class="mix col-lg-4 col-md-4 col-sm-12 col-12 @items.CatId">
                                    <div class="box-item">
                                        <a id="catresim" class="resim" href="@Url.Content("~/resimler/" + @items.ResimYolu)" asp-append-version="true" 
                                           data-rel="lightcase">
                                            <img class="img-fluid resim" src="@Url.Content("~/resimler/" + @items.ResimYolu)" alt="item1" />
                                        </a>
                                        <a class="resim" href="~/resimler/@items.ResimYolu" data-rel="lightcase">
                                            <h3 id="catitem" class="item-name mb-0">@items.Baslik</h3>
                                        </a>
                                        <span id="catname" class="cat-name">@items.İcerik</span>
                                    </div>
                                </div>
    
                            }
     public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
                //services.AddMemoryCache();
                //services.AddSession();
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);           
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
           
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                      name: "areas",
                      template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    );
                });
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
                app.UseHttpsRedirection();
                app.UseCookiePolicy();
               
    
            }

    Tuesday, October 1, 2019 3:49 PM
  • User753101303 posted

    Hi,

    Seems you have a controller which is supposed to return an image (the name is in the db and you want to retrieve this from a file ?)

    So far what the controller code you shown doesn't add at best a row to a db but there is nothing showing how the file content is supposed to be return.

    Also 

    if (resimyolu != null)

    might skip filling the object in which case it would have at best default values. IMO your app should be coded for what you expect and in particular it is best if it fails where you have an actual problem rather than testing if something that shoudln't happen happens to prevent a problem and have anyway some other problem later in your app.

    Tuesday, October 1, 2019 4:08 PM
  • User475983607 posted

    Aliyilmaz

    But still I dont get image. I try like this.

    Your updated code; Url.Content() is incorrect.  Url.Content returns the absolute path of the image.  The img tag expects a virtual path.

    <img class="img-fluid resim" src="@Url.Content("~/resimler/" + @items.ResimYolu)" alt="item1" />

    Ironically, your original construct will work.  

    <img src="~/resimler/@item.ResimYolu" width="150" height="150" />

    This fact is confirmed in you similar threads as well as the sample code above.  For example.

            // Home/ImageDemo
            [HttpGet]
            public IActionResult ImageDemo()
            {
                //Mock image path result set
                List<string> images = new List<string>() { @"switch.png", @"switch.png" };
                return View(images);
            }
    
    @model List<string>
    
    @{
        ViewData["Title"] = "ImageDemo";
    }
    
    <h1>ImageDemo</h1>
    <div>
        @foreach(string s in Model)
        {
            <img src="~/img/@s" />
        }
    </div>

    HTML results.

    <div>
            <img src="/img/switch.png"><img src="/img/switch.png">
            
    </div>

    The community has recommended several times that you take advantage of dev tools to view the HTML source and verify the HTML is expected.  View the network trace tool for 404 errors.  The community also recommended adding the img URL to the browser's address bar to see if the image renders in the browser.  We've received no feedback on the status of these basic troubleshooting steps.

    The fact that you have been having such difficulty for several days seems like you might be using a 3rd party library that is causing this issue.  The troubleshooting step above will help highlight the bug in your design and code.

    Tuesday, October 1, 2019 6:01 PM
  • User197255166 posted

    Hi,

    When I click link browser I dont see image. When I look at the network part of the browser, it's 304. I dont use 3.party.

    Note : If there is time available, I would be very happy to connect with teamviewer to solve the problem.

    http://localhost:50026/resimler/banner2.jpeg

    Wednesday, October 2, 2019 5:24 PM
  • User475983607 posted

    When I click link browser I dont see image. When I look at the network part of the browser, it's 304.

    A 304 is a cached page.  Press ctrl-F5 which forces the browser to refresh all content.

    Secondly, you still do not answer all the questions...  Does the image display if you add the following URL in browser's address bar and press enter?

    http://localhost:50026/resimler/banner2.jpeg

    Wednesday, October 2, 2019 5:45 PM
  • User197255166 posted

    Hi,

    Yes I paste link browser address. But dont see image. Also I send message mgebhard.

    Wednesday, October 2, 2019 6:01 PM
  • User475983607 posted

    Yes I paste link browser address. But dont see image.

    What happened?  Did you get a 404?

    Wednesday, October 2, 2019 6:12 PM
  • User197255166 posted

    No not 404. Only blank page.

    Wednesday, October 2, 2019 6:27 PM
  • User475983607 posted

    Aliyilmaz

    No not 404. Only blank page.

    That does not make sense.  Have you tried opening the file directly from the solution explorer?  Are you using Dev tools?

    Wednesday, October 2, 2019 7:03 PM
  • User753101303 posted

    I still don't see anywhere how you return a content. if you want to return the content of a file stored somewhere and whose path/name is saved to your datbase you should likely return a https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.physicalfileresult?view=aspnetcore-2.2 at some point.

    Wednesday, October 2, 2019 7:12 PM
  • User197255166 posted

    Hi,

    Please can anyone help me with teamviewer. I shared everything. But seeing this live, this work is solved.

    Wednesday, October 2, 2019 8:01 PM
  • User711641945 posted

    Hi Aliyilmaz,

    HTTP 304 is a redirect not an error. It means it is loading the image from the cache. If you have been making changes try clearing your cache or opening the browser in private browsing mode so it won't load from it. It may have cached an image/location that is invalid still which is why it isn't loading.

    And could you share a detailed code about your controller action that could reproduce your issue?

    Reference: 

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304

    https://clear-my-cache.com/en/windows.html

    Best Regards,

    Rena

    Friday, October 4, 2019 6:12 AM
  • User197255166 posted

    Hi,

    I shared all code. what else do I have to share. I would appreciate it if we could solve 10 minutes if the computer provides a connection.

    Saturday, October 5, 2019 9:34 AM
  • User711641945 posted

    Hi Alilyilmaz,

    You posts part of the code not the entire code in your controller and cshtml file.Could you share your simple demo without disclosure of personal information?

    And did you try to clear your cache or opening the browser in private browsing mode?

    Best Regards,

    Rena

    Tuesday, October 8, 2019 8:02 AM