尝试将图像上载到数据库时,“对象引用未设置为对象实例”错误 [英] 'Object reference not set to instance of an object' error when trying to upload image to database

查看:138
本文介绍了尝试将图像上载到数据库时,“对象引用未设置为对象实例”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#将图像上传到SQL数据库。我从另一个站点找到了一些在测试项目中完美运行的代码。但是当我复制并粘贴代码并将其放入我的实际项目时,它给了我一个对象引用没有设置为对象的实例错误。这对我没有意义,因为它在测试项目中运行得很好。代码如下...

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.

推荐答案

可能的问题:

您正在从 HttpPostedFile.InputStream 读取两次而不重置头寸。

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

这篇关于尝试将图像上载到数据库时,“对象引用未设置为对象实例”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆