Hey guys,

For some reason I cannot get an image I have uploaded to display when I try to render it through an <img> tag within a response.write() API Call in C#. Here is my code:

protected void uploadFiles(object sender, EventArgs e)
    {
        HttpFileCollection allFiles = Request.Files;
        for (int i = 0; i < allFiles.Count; i++)
        {
            HttpPostedFile singleFile = allFiles[i];
            try
            {
                if (singleFile.ContentLength > 0)
                {
                    //Get the name of the file
                    string fileName = singleFile.FileName.Substring(singleFile.FileName.LastIndexOf("\\") + 1);
                    //The name of the image with the Images
                    string image = "Images"; +"//" + fileName;

                    //Save it to the server
                    singleFile.SaveAs(Server.MapPath(image));

                    string htmlOutPut = "File Size: " +
                     singleFile.ContentLength + "kb<br>";

                    htmlOutPut += "File Name: " + fileName + "</ br>";

                    //SOURCE OF ERROR. The image is never displayed
                    htmlOutPut += "<img src=" + image + "/>";
                    Response.Write(htmlOutPut);
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
         }

I'm basically uploading it and then saving it and just trying to display the image by using an image tag but the image I'm trying to upload does not show up. The only thing that shows up is the standard small image not found thumbnail. I've tried numerous things such as ResolveUrl and it still does not render the image. In addition I also made a static <img> tag within my form and was able to display an image from the same directory I'm uploading and saving the image to!

Can anyone give me some advice on how to get this working?

Dani AI

Generated

Broken-image means the browser cannot fetch the file. The original semicolon bug that found would definitely explain a missing filename, and ’s tip about writing output once (after you build it) is good practice — but there are a few other, common causes to check before assuming it’s an ASP.NET or browser glitch.

The important rule: the src attribute must be a web-accessible URL (virtual or relative), not a server filesystem path. Server.MapPath(...) returns something like C:\inetpub\... — that is correct for saving the file, but not for use in the <img> tag. Likewise, passing a physical path into ResolveUrl is incorrect. Build a virtual URL (for example ~/Images/filename.jpg or /Images/filename.jpg) and use that for src. Also make sure you sanitize the filename (use Path.GetFileName) and create the folder if it’s missing.

Example of a safe flow (save on server, then reference a virtual URL):

var imagesFolder = Server.MapPath("~/Images");
System.IO.Directory.CreateDirectory(imagesFolder);
var serverFile = System.IO.Path.Combine(imagesFolder, Path.GetFileName(fileName));
singleFile.SaveAs(serverFile);

var virtualUrl = VirtualPathUtility.ToAbsolute("~/Images/" + Path.GetFileName(fileName));
htmlOutPut += "<img src=\"" + virtualUrl + "\" alt=\"uploaded image\" />";

Quick troubleshooting checklist:

  • View the generated <img> in browser “View Source” and copy the src into the address bar to see the HTTP status (404/403 etc.).
  • Confirm the file actually exists at the server path you saved to.
  • Ensure the Images folder is inside the web application and has proper read permissions for IIS.
  • Keep Response.Write outside the upload loop and build htmlOutPut incrementally.
    If direct file access isn’t appropriate, serve images through a handler (ASHX/controller) that streams the file with the correct Content-Type.

Recommended Answers

All 4 Replies

Response.Write should be outside the for loop.

protected void uploadFiles(object sender, EventArgs e)
    {
       ...
        for (int i = 0; i < allFiles.Count; i++)
        {
             ...... 
        }
      Response.Write(htmlOutPut);

The code...

string image = "Images"; +"//" + fileName;

Should be..

string image = "Images" +"//" + fileName;

You have added an unnecessary semi-colon which will effectively terminate that statement so the filename never gets added.

Surprised your IDE did not flag up a warning on compilation - mine certainly did!

Thanks for the quick replies.

Hey 'Crappy Coder; I took out the semicolon and still this image does not display (I actually had a typo when I was pasting it into the code tags).

I've tried numerous things but nothing seems to work! So far I've tried:

htmlOutPut += "<img src=&quot;" + Server.MapPath(image) + "&quot; />";

Also

htmlOutPut += "<img src='" + ResolveUrl(Server.MapPath(image)) + "' />";

And

htmlOutPut += "<img src=" + image + " />";

But nothing displays! Do I need to convert this to a bit map before I can display it?

Ideally you should be using a virtual or relative path so using Server.MapPath is not to be recommended as it gives a hacker a chance to peruse your directory structure.

Have you tried...

<img src="Images/<imagename>" />

BTW what is the value of htmlOutPut AFTER you have assigned the image name to it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.