'Object reference not set to instance of an object' error when trying to upload image to database

我是研究僧i 提交于 2019-12-12 02:17:01

问题


I am trying to upload an image to a SQL database using C#. I found some code from another site that worked perfectly in a test project. But when I copied and pasted the code and put it into my actual project, it gives me an 'Object reference not set to an instance of an object' error. This makes no sense to me because it worked just fine in the test project. The code is as follows...

protected void btnAddDevice_Click(object sender, EventArgs e)
{
    byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
    HttpPostedFile Image = FileUpload1.PostedFile;
    Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
    SqlConnection myConnection = new SqlConnection(cnString);
    SqlCommand storeimage = new SqlCommand("insert into ImageTable (img,description,width,height) values(" + "@image,'Description',@imagesize,@imageheight)", myConnection);
    storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
    System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = img.Width;
    storeimage.Parameters.Add("@imageheight", SqlDbType.BigInt, 99999).Value = img.Height;
    myConnection.Open();
    storeimage.ExecuteNonQuery();
    myConnection.Close();
}

I'm getting the error on the first line inside the method when the byte is being set. I've looked everywhere and tried many different things, but I have no idea why I'm getting this error. Any help would be much appreciated.


回答1:


Put a breakpoint on the first line, and look at the variables involved. One will be null when your expecting a value.

Most likely FileUpload1.PostedFile is null. Insure that a file has been specified before trying to read its bytes.




回答2:


Possible issue:

You are reading from HttpPostedFile.InputStream twice without resetting the position.



来源:https://stackoverflow.com/questions/6359302/object-reference-not-set-to-instance-of-an-object-error-when-trying-to-upload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!