需要帮助使用 asp.net 将图像保存在 sql 数据库中

发布于 2024-08-10 05:38:55 字数 2530 浏览 4 评论 0原文

我试图将员工图像保存在员工数据库中。我在数据库表 empid、empname、empimage 中有三个字段。这是我的数据库部分。

CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

在按钮单击事件中,我编写了以下代码:

SqlConnection connection = null;
    try
    {
        FileUpload img = (FileUpload)imgUpload;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = imgUpload.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        // Insert the employee name and image into db
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg)SELECT @@IDENTITY";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
        cmd.Parameters.AddWithValue("@eimg", imgByte);
        int id = Convert.ToInt32(cmd.ExecuteScalar());
        lblResult.Text = String.Format("Employee ID is {0}", id);
    }
    catch
    {
        lblResult.Text = "There was an error";
    }
    finally
    {
        connection.Close();
    }

这是我的表单:

<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:FileUpload ID="imgUpload" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
        onclick="btnSubmit_Click" />   
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp      
    <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />  
    <asp:Image ID="Image1" style="width:200px" Runat="server" />   

但是当我上传任何图像并单击提交按钮时,出现此错误“对象引用未设置为对象的实例”。请有人指出我的错误。

谢谢, 苏米特

I trying to save employee image in employee database. I have three field in database table empid, empname, empimage. Here is my database part.

CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

In the button click event, i have written the following code:

SqlConnection connection = null;
    try
    {
        FileUpload img = (FileUpload)imgUpload;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = imgUpload.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        // Insert the employee name and image into db
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg)SELECT @@IDENTITY";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
        cmd.Parameters.AddWithValue("@eimg", imgByte);
        int id = Convert.ToInt32(cmd.ExecuteScalar());
        lblResult.Text = String.Format("Employee ID is {0}", id);
    }
    catch
    {
        lblResult.Text = "There was an error";
    }
    finally
    {
        connection.Close();
    }

And Here is my form:

<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
        
    <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
        
    <asp:FileUpload ID="imgUpload" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
        onclick="btnSubmit_Click" />   
                  
    <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />  
    <asp:Image ID="Image1" style="width:200px" Runat="server" />   

But when I am uploading any image and clicking on submit button getting this error "Object reference not set to an instance of an object." Pls somebody point out my error.

Thanks,
Sumit

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

围归者 2024-08-17 05:38:55

仅当对象未初始化并且您尝试引用它时,才会发生对象引用错误。这可以是您在代码中引用的任何对象。如果在调试时单步执行代码,您可以准确地看到哪个引用为空。

您有一个 if 语句来初始化 imgByte 对象:

  imgByte = new Byte[File.ContentLength];

如果 img 对象结果为 null,则该代码不会运行。然后,您在此处引用 imgByte,无论 img 是否为 null:

  cmd.Parameters.AddWithValue("@eimg", imgByte);

检查 HttpPostedFile 对象本身是否为 null,并将 imgByte 对象初始化移到 if 语句之外。此外,名称 File 已被 System.IO.File 对象使用。为了安全起见,您可能需要重命名它。

Object Reference errors only occur when an object is not initialized and you try to reference it. This could be any object you are referencing within your code. If you step through the code while debugging, you can see exactly which reference is null.

You have an if statement that initializes the imgByte object:

  imgByte = new Byte[File.ContentLength];

If the img object turns out to be null, that code does not run. Then you reference the imgByte here, regardless of whether or not the img was null:

  cmd.Parameters.AddWithValue("@eimg", imgByte);

Check the the HttpPostedFile object itself is not null and move your imgByte object initialization outside the if statement. Also, the name File is already used by the System.IO.File object. You may want to rename it just to be safe.

小伙你站住 2024-08-17 05:38:55

我会稍微重新安排一下您的 ADO.NET 代码 - 使其安全且更可靠;另外,我会确保用分号分隔“sql”字符串中的两个 SQL 语句,以使 SQL 清楚这是两个命令,真的:

string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;

using(connection = new SqlConnection(conn))
{
     string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " + 
                      "VALUES(@enm, @eimg); SELECT @@IDENTITY";

     using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
     {
        cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
        cmd.Parameters.AddWithValue("@eimg", imgByte);

        connection.Open();

        int id = Convert.ToInt32(cmd.ExecuteScalar());

        connection.Close();

        lblResult.Text = String.Format("Employee ID is {0}", id);
     }
}

这运气好吗?否则,您应该真正单步执行调试器中的代码,并查看代码中何处引用了 NULL 的内容(并且不检查该条件)。

马克

I would rearrange your ADO.NET code a bit - make it safe and more reliable; also, I would make sure to separate the two SQL statements in your "sql" string by a semicolon to make it clear to SQL that this is two commands, really:

string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;

using(connection = new SqlConnection(conn))
{
     string sqlStmt = "INSERT INTO dbo.EmpDetails(empname, empimg) " + 
                      "VALUES(@enm, @eimg); SELECT @@IDENTITY";

     using(SqlCommand cmd = new SqlCommand(sqlStmt, connection))
     {
        cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
        cmd.Parameters.AddWithValue("@eimg", imgByte);

        connection.Open();

        int id = Convert.ToInt32(cmd.ExecuteScalar());

        connection.Close();

        lblResult.Text = String.Format("Employee ID is {0}", id);
     }
}

Any luck with this?? Otherwise you should really step through the code in the debugger and see where in your code you reference something that is NULL (and you don't check for that condition).

Marc

北城孤痞 2024-08-17 05:38:55

当我调试这段代码时,我
在此遇到异常
行...”字符串 conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
例外是:未设置对象引用
到对象的实例。

您需要将名为 EmployeeConnString 的连接字符串添加到 web.config 中。

您的异常处理程序不会区分异常发生的具体位置,并且会针对任何可能的错误发出一条错误消息。

While i am debugging this code i am
getting exception in this
line..."string conn =
ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;"
Exception is: Object reference not set
to an instance of an object.

You need to add a connection string named EmployeeConnString to web.config.

Your exception handler does not distinguish where exactly an exception occurred, and issues a single error message for any possible error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文