How to view/show image from file server path on button click

Gani_tpt 1,586 Reputation points
2024-04-27T18:06:29.1133333+00:00

i am developing asp.net application.

i am uploading many image documents in file server path like example (\server2\prj1\picture1.png)

At the same time, i want to view/show the same file (image document) on button click event.

How to show this image through modal popup window.

Note : i want only button click event not in gridview control.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,285 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,299 questions
{count} votes

Accepted answer
  1. Albert Kallal 4,806 Reputation points
    2024-04-29T18:34:09.6033333+00:00

    Ok, there are several issues here.

    First issue is you have to decide if you going to map the server path you using for storing those files to the web site. This is not necessary required, but often you will want such a setup. In other words, if the file location is outside of the root folder of the web site? Then you either have to map the external folders to the web site, or use code behind to send the file to the browser.

    Obviously using code behind is far more secure, but this means that no valid URL to the files can be used. For customer files and security, I prefer this approach. If you map the folder to the web site, then any user can type in any valid URL, and even view files that don't belong to a give customer.

    So, your idea of adding rows to a database is a good idea. So, the only real decision here is do you want to map those external folders (even on another server) to the web site or not? As noted, if yes, then any valid URL can see or view or use any of those files. (not great for security, but often ok for say a bunch of pictures or documents that you want all users to enjoy and use).

    The other issue of course is what is to occur if two users (or one user) uploads files with the same name? This is possible since I might have the same file name in several different folders, but with the final server folder being one folder with files, then that's a issue you have to deal with. And of course several different users might upload files with the same name.

    So, you can map those external folders to the web site. (this is called a virtual folder). This means that the web site and valid URL's will exist from the web site URL to those folders. As I suggested, for customer files, this is not a great idea.

    Keep in mind that while the web site and URL's typed in must be valid, your code behind does NOT use those URL's, and you are using plain jane fully valid windows path names in your code behind. This gives rise to the ability of NOT using virtual folders to allow valid URL's to those files, but code behind is still 100% free to save, open, and transmit such files to the end user. And I often for reasons of management I do create a new folder for each customer. (based on their project number, project ID, or even their logon ID). So, while a database to keep track of the files uploaded, what user uploaded them, and provide the user with a UI is a good idea? I would consider creating a folder for each customer, as that also means that your file system does not have 100's and 100's of files in one folder, as that makes management of such a system difficult, not to mention performance issues with 100's of files being placed in the same folder.

    So, looking at all of the above? Turns out spending time on the design of how this is to work is more valuable then that of the coding part (the coding part turns out to be rather easy once you identified all of the above issues, and make a decision for each of the above considerations).

    So, assuming that server and folder path is outside of the root folder of the web site?

    And assuming that you don't setup a URL mapping (virtual folder) to that file folder or file server for the files?

    Then for a simple button click to display the file (picture), then the following c# code will load the file into the picture:

    Say this markup:

                <asp:Button ID="cmdShowPicture" runat="server" Text="Load picture from file"
                    OnClick="cmdShowPicture_Click"                
                    />
    
                <br />
                <br />
                <br />
                <asp:Image ID="Image1" runat="server" Width="48px" />
    
    

    And our code behind is this:

            protected void cmdShowPicture_Click(object sender, EventArgs e)
            {
                string sInternalFileName = @"c:\test\balls\b5.png";
    
                string sMineType = MimeMapping.GetMimeMapping(sInternalFileName);
    
                byte[] rawFile = File.ReadAllBytes(sInternalFileName);
                Image1.ImageUrl = 
                    $@"data:{sMineType};base64,{Convert.ToBase64String(rawFile)}";
    
    
            }
    
    

    And the result is this:

    loadpic

    Now, I did not pop the image with a button click, since I wanted to keep 100% sperate as to how you can read a file from code behind, and load the image control. One of course can add extra code to pop some dialog to display the picture, but we want to break this down into smaller bite sized steps here. So, above shows how to load the image control, and load it from a raw file placed in a folder that is likely outside of the root folder.

    As noted, while you did not want some GiveView example, in practice, you need a way to display the list of user files. Hence, loading up a GridView, (or listview or repeater) makes the most sense to display a list of choices to the user. And the above code behind can thus be used to load up that image. After that, the moving parts to pop the picture as some dialog or whatever can be achieved with the other posted code in this thread.

    So, assuming that when the user up-loads a file, you added a row to a database? (not clear if you looking for code on how to do this part), then the end result is a database with some rows, no doubt with one column that defines the current user logon id. So, we can now for example display the list of views, and have a row click button for the user to click on, or even just display all of the pictures anyway.

    So, with a database, then we can create a GridView like this:

    User's image

    So, in above when I click on the view, I could pop the image, and using the above code shared here?

    Well, then the logic would be:

    Get the row click from the button.

    Get the file name from the database.

    Load the image (say a hidden div we are to pop).

    Pop the image.

    So, say a gridview like this:

    gpicpop

    The code behind is now say this:

            protected void cmdView_Click(object sender, EventArgs e)
            {
                LinkButton btn = (LinkButton)sender;
                GridViewRow gRow = (GridViewRow)btn.NamingContainer;
    
                string sFile = gRow.Cells[0].Text;
                string sInternalFile = $@"C:\Users\Kalla\source\repos\CSharpWebApp\UpLoadFiles\{sFile}";
    
                // load our image control
                string sMineType = MimeMapping.GetMimeMapping(sInternalFile);
    
                byte[] ImageBytes = File.ReadAllBytes(sInternalFile);
                Image1.ImageUrl = $@"data:{sMineType};base64,{Convert.ToBase64String((byte[])ImageBytes)}";
    
                // pop the picture
                string sJava = "mypop();";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(),"mypop", sJava, true);
    
            }
    
    

    So, it is much the same code as before, but we added the GridView to display the files the user uploaded. And then we also added some code to pop the dialog. I'm using a jQuery.UI dialog, and that JavaScript code on the page was this:

            <div id="myimagepop" style="display:none;text-align:center">
    
                <asp:Image ID="Image1" runat="server"  Width="75%"/>
    
            </div>
    
            <script>
    
                function mypop() {
                    var mydiv = $("#myimagepop")
    
                    mydiv.dialog({
                        modal: true,
                        title: "My Picture", closeText: "",
                        width: "50%",
                        dialogClass: "dialogWithDropShadow",
                        buttons: {
                            Ok: (function () {
                                mydiv.dialog("close")
                            })
                        }
                    });
    
                }
    
           </script>
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. hossein jalilian 3,020 Reputation points
    2024-04-27T21:12:24.16+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    You can use a modal popup window to display the image when a button is clicked:

    • Add a button and a hidden HTML element (such as a div) to the ASP.NET page where you want to display the modal popup window
    <button id="btnShowImage" runat="server" onclick="ShowImageModal()">Show Image</button>
    <div id="imageModal" class="modal">
      <span class="close" onclick="CloseImageModal()">&times;</span>
      <img id="imgPreview" src="#" alt="Preview">
    </div>
    
    
    • Add JavaScript functions to show and close the modal popup window
    <script>
    function ShowImageModal() {
      var modal = document.getElementById('imageModal');
      var img = document.getElementById('imgPreview');
     
      img.src = "images_path";
      modal.style.display = "block";
    }
    function CloseImageModal() {
      var modal = document.getElementById('imageModal');
      modal.style.display = "none";
    }
    </script>
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful


  2. Lan Huang-MSFT 25,871 Reputation points Microsoft Vendor
    2024-04-30T09:33:46.47+00:00

    Hi @Gani_tpt,

    If you don't want to use the gridview control, you can try using Session to get the file just uploaded.

    Below is a simple example.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />
                <hr />
                <asp:Button ID="View" runat="server" Text="Button" OnClick="Display" />
                
                <div>
                    <div class="modal fade" id="myModal" role="dialog">
                        <div class="modal-dialog">
                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">
                                        &times;</button>
                                </div>
                                <div class="modal-body">
                                    <asp:Image ID="img" runat="server" Width="200px" Height="200px" />
                                </div>
                            </div>
                        </div>
                        <script type='text/javascript'>
                            function openModal() {
                                $('[id*=myModal]').modal('show');
                            }
                        </script>
                    </div>
                </div>
            </div>
        </form>
    </body>
    </html>
    
    protected void UploadFile(object sender, EventArgs e)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        Session["as"] = fileName;
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void Display(object sender, EventArgs e)
    {
        string a = Session["as"].ToString();
        string filePath = Server.MapPath("~/Uploads/") + a;
        byte[] byteArray = File.ReadAllBytes(filePath);                   
        string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String(byteArray);
        img.ImageUrl = imageUrl;
        ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openModal();", true);
    }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.