I have the following asp.net C# code to upload an image, and when I try to run it and select the file to upload, it does not recognize that I have selected a file to upload, so I get the message "file not uploaded successfully. I get the following error when trying. Object reference not set to an instance of an object.
I believe I have to add code, to instantiate. I am new to this, and I believe I do not have the correct syntax. I have a data entry form where the File Upload. Can someone tell me what I need, I think I need to add a declaration, as in Line 3 (with ******), but what I have may not be correct if it is not setting the file I am trying to upload, the debugger shows no file, although I am selecting one. Thanks.
See code below
protected void ButImg_Click(object sender, EventArgs e)
{
******FileUpload fileImg = (FileUpload)this.FindControl("fileImg");*****
if (fileImg.HasFile)
{
string imgfile = Path.GetFileName(fileImg.PostedFile.FileName);
string savePath = Path.Combine(ConfigurationManager.AppSettings["ImagesFolder"], imgfile);
fileImg.SaveAs(Server.MapPath("UsrImage/"+ imgfile));
_connstr = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
/* Save file to Ticket Attachments folder */
if (System.IO.File.Exists(savePath))
{
System.IO.File.Delete(savePath);
}
SqlConnection sqlconn = new SqlConnection(_connstr);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(_procUpdateImage);
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Connection = sqlconn;
sqlcomm.Parameters.AddWithValue("@UsrID", this.txtUsrID.Text);
sqlcomm.Parameters.AddWithValue("@ImageName", imgfile);
sqlcomm.Parameters.AddWithValue("@ImagePath", "Images/" + imgfile);
sqlcomm.Parameters.AddWithValue("@UsrID", _UsrName);
sqlcomm.ExecuteNonQuery();
LitImg.Text = "Image saved successfully";
sqlconn.Close();
fileImg.SaveAs(savePath);
}
else
{
LitImg.Text = "Image not saved successfully";
}
}
.aspx web form for Upload control
<td class="tdSingle">Usr Image</td>
<td class="tdSingle">
<asp:FileUpload ID="fileImg" runat="server"></asp:FileUpload><br/>
<asp:Button ID="ButImg" runat="server" Text="Image Save" OnClick="ButImg_Click" ></asp:Button><br/>
<p>
<asp:Literal ID="LitImg" runat="server"></asp:Literal>
</p>
</td>