开发者

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

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.Conten开发者_开发问答tLength);
    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.


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.


Possible issue:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜