2009-11-08 1 views
0

직원 이미지를 직원 데이터베이스에 저장하려고합니다. 데이터베이스 테이블 empid, empname, empimage에 세 개의 필드가 있습니다. 여기 내 데이터베이스 부분입니다. 내가 어떤 이미지를 업로드하고 클릭하고 때asp.net을 사용하는 sql 데이터베이스의 이미지 저장에 도움이 필요합니다.

<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" /> 

그러나 : 버튼 클릭 이벤트에서

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(); 
    } 

을 그리고 여기 내 양식입니다 이 오류를 가져 오는 버튼을 제출하십시오 "개체 참조가 개체의 인스턴스로 설정되지 않았습니다." 누군가 내 실수를 지적했다. 객체가 초기화 당신이 그것을 참조하려고하지 않을 때

덕분에, 수밋

+0

누구나 (자신을 포함) 호의를 베풀고 코드를 올바르게 포맷 할 수 있습니까?또한 호출 스택 – mfeingold

+0

을 포함 시키십시오. 폼을 표시하고, 또한 어떤 라인에서 오류가 발생합니까? – AnthonyWJones

답변

1

개체 참조 오류 만 발생합니다. 이것은 코드 내에서 참조하는 모든 객체 일 수 있습니다. 디버깅하는 동안 코드를 단계별로 실행하면 정확히 어떤 참조가 null인지 확인할 수 있습니다. 예 : img 객체가 null로 밝혀지면

imgByte = new Byte[File.ContentLength]; 

, 그 코드가 실행되지 않습니다

당신은 imgByte 객체를 초기화 if 문이있다.

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

이 (가) HttpPostedFile 개체 자체가 null이 아닌 확인하고 if 문 밖에서 imgByte 개체 초기화를 이동 : 그럼 당신은 여부에 관계없이 IMG의 널 (null)이었다, 여기에 imgByte를 참조합니다. 또한 File이라는 이름은 이미 System.IO.File 개체에서 사용됩니다. 안전을 위해 이름을 바꿀 수도 있습니다.

+0

Visual Studio 디버거에는 처리중인 경우에도 모든 .NET 예외에 대한 디버그 기능이 포함되어 있습니다. 그것은 매우 유용하고, 나는 항상 그걸로 달린다. 디버그 메뉴에서 "예외 ..."를 클릭하십시오. –

0

나는 당신의 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 인 것을 참조하고 그 조건을 확인하지 않습니다.

마크

+0

안녕이 코드에서 디버깅하는 동안이 줄에서 예외가 발생합니다 ... "string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString "]. ConnectionString;" 예외 : 개체 참조가 개체의 인스턴스로 설정되지 않았습니다. – Sumit

+0

그러면 분명히 app.config 또는 web.config에 "EmployeeConnString"이라는 연결 문자열이 없습니다! –

0

내가이 라인에서 예외를 받고 나는이 코드 ... "문자열 CONN = ConfigurationManager.ConnectionStrings ["EmployeeConnString "] 디버깅하고 있지만 ConnectionString을을;." 예외 : 개체 참조가 개체 인스턴스에 으로 설정되지 않았습니다.

web.config에 EmployeeConnString이라는 연결 문자열을 추가해야합니다.

예외 처리기는 예외가 발생한 정확한 위치를 구분하지 않고 가능한 오류에 대해 단일 오류 메시지를 발행합니다.

관련 문제