0

I have been trying to upload images via a file upload control. The file is not being uploaded and I keep getting the following error:"Cannot access a closed file."

I am unsure as to why I am getting this error, any assistance would be appreciated.

My code: First is the code that grabs the image and creates the 'preview'

protected void btnupload_Click(Object sender, EventArgs e)
    {
        Session["Image"] = flupGalImg.PostedFile;
        Stream fs = flupGalImg.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        imgGalImg.ImageUrl = "data:image/png;base64," + base64String;
        imgGalImg.Visible = true;

    }

My code that calls my business logic code:

else if(btnaddedit.Text == "Add item")
    {
        if(txtItemTitle.Text != "")
        {
            if(txtItemDescription.Text != "")
            {
                if(Session["Image"] != null)
                {
                    HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];
                    int alb;
                    int.TryParse(hdnAlbId.Value, out alb);
                    if(newsLogic.CreateNewGalleryItem(txtItemTitle.Text, txtItemDescription.Text, alb, postedFile) == true)
                    {
                        // Do something.   
                    }

                }
            }
        }
    }

And finally my business logic code:

// create gallery item
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
public bool CreateNewGalleryItem(string itemTitle, string itemDescription, int itemAlbum, HttpPostedFile itemFile)
{
    string folderpath = @"~/Images/GalleryImages/";
    string filename = Path.GetFileName(itemFile.FileName.ToString());
    bool itemCreated = false;
    string itemImgPath;
    try
    {
        itemImgPath = Path.Combine(folderpath + filename);
        string itemImgUploadPath = Path.Combine(HttpContext.Current.Server.MapPath(folderpath) + filename); 
        itemFile.SaveAs(itemImgUploadPath);
        galAdp.CreateGalleryItem(itemTitle, itemDescription, itemImgPath, itemAlbum);
        itemCreated = true;
    }
    catch (Exception er)
    {
        itemCreated = false;
        string consmsg = er.Message;
    }
    return itemCreated;
}

My 'image preview' works just fine. The error is thrown on this line of the business logic: itemFile.SaveAs(itemImgUploadPath);

When I did a google search (well lots of google searches) I read that it may be the file size so I increased the max allowed content in the web.config but nothing changed.

Any ideas as to what I am doing wrong?

M_Griffiths
  • 547
  • 1
  • 7
  • 26

0 Answers0