简体   繁体   中英

Image Preview asp.net with c#

I'm working on getting an image into a picturebox on asp.net from a list-box , the list-box reads a directory and then populates the jpegs in the file. This needs to be done in c#, at the moment I have a rough idea on how it's done but I'm not getting any picture showing:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
          DirectoryInfo infoDir = new DirectoryInfo(@"G:/Test_Directory");            
          FileInfo[] infoFile = infoDir.GetFiles("*.jpeg");
          foreach( FileInfo file in infoFile )
          {
               lstDirectory.Items.Add(file.Name);
          }
        }    
    }

    protected void lstDirectory_SelectedIndexChanged(object sender, EventArgs e)
    { 
        Server.MapPath(lstDirectory.SelectedValue.ToString());
        imageChange.ImageUrl = lstDirectory.SelectedValue.ToString();            
    }
}

it could be a case of the path not being correct, or maybe something else. Can someone could direct me to where I'm going wrong.

You are not using the result of MapPath . Try this.

    var img = Server.MapPath(lstDirectory.SelectedValue.ToString());
    imageChange.ImageUrl = img;  

UPDATE: Your image files folder seems to be outside of web folder, move it inside. There is no simple way to make it work otherwise.

I would suggest you to add New folder in your solution and add all your images in to it...

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
          DirectoryInfo infoDir = new DirectoryInfo(Server.MapPath("Images"));//this is the image foled name            
          FileInfo[] infoFile = infoDir.GetFiles("*.jpeg");
          foreach( FileInfo file in infoFile )
          {
               lstDirectory.Items.Add(file.Name,"Images/"+file.Name);
             //here you are setting relative path of images in your value field
          }
        }    
    }

Then set the image path to thr Server.MapPath as follow....

protected void lstDirectory_SelectedIndexChanged(object sender, EventArgs e)
    { 
        if(File.Exists(Server.MapPath(lstDirectory.SelectedValue.ToString())))
        {
          imageChange.ImageUrl =Server.MapPath(lstDirectory.SelectedValue.ToString());            
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM