Search code examples
c#asp.netimage-uploadingweb-controls

ASP.NET: Image URL is correct, but image does not display


I know this has been asked before, as it's a rookie question, but the other answers on here did not clarify it for me. I an uploading a file then providing a preview. The click event of my upload button is this:

protected void UploadFile (object sender, EventArgs e) {

    string folderPath = Server.MapPath ("~/Uploads/");

    // If folder does not exist, create it.
    if (!Directory.Exists (folderPath))
        Directory.CreateDirectory (folderPath);         

    //Save the File to the Directory (Folder).
    FileUpload.SaveAs (folderPath + Path.GetFileName (FileUpload.FileName));

    //Display the Picture in Image control.
    imgItem.ImageUrl = folderPath + Path.GetFileName (FileUpload.FileName);
}

The upload works fine, but the image control (imgItem) does not display the picture. When I trace it, the URL looks perfect. The URL is:

"C:\\MyStuff\\Source\\Inventory\\Inventory\\UserInterface\\Uploads\\sample.jpg"

That should have worked. What in the world am I doing wrong?

EDIT: I don't feel that this is a good solution at all, but I've found that the program works as expected if I change the last line to this:

imgItem.ImageUrl = "~/Uploads/" + Path.GetFileName (FileUpload.FileName);

Don't anyone have a cleaner, less hardcodey solution?


Solution

  • imgItem.ImageUrl = "~/Uploads/" + Path.GetFileName (FileUpload.FileName);