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

1.9k views Asked by At

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?

2

There are 2 answers

0
John On BEST ANSWER

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

0
Alex - Tin Le On

Well, the

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

is actually the file path, not the URL. Since you use the word "URL", I assume that you're building a web site. Which means you need an proper URL (e.g. http(s)://yourdomain.com/Source/Inventory/..../sample.jpg)

If you don't how what is the url for your file path, you can use virtual folder in IIS to map it. https://docs.kentico.com/k11/installation/deploying-kentico-to-a-live-server/creating-virtual-directories-and-application-pools-in-iis-7-5-and-7-0