2017-10-18 4 views
1

저는 ASP & C#을 처음 접했고이를 수행하는 방법을 찾을 수 없었습니다.SQL BLOB을 사용할 수 없을 때 .ashx에서 기본 이미지를로드하는 방법

.ashx 같은 파일을 통해 BLOB를로드 중이므로 <img src="getimage.ashx" />과 같은 파일이 제대로 작동하지만 가끔은 BLOB가 없거나 비어 있습니다.

여기

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DataSource.iMIS.Connection"].ConnectionString); 
     SqlCommand cmd = new SqlCommand("SELECT PICTURE_LOGO FROM Name_Picture WHERE ID = @EmpID", con); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.Add("@EmpID", id); 

     con.Open(); 
     byte[] pict = (byte[])cmd.ExecuteScalar(); 
     con.Close(); 

     ctx.Response.ContentType = "image/bmp"; 
     ctx.Response.OutputStream.Write(pict, 0, pict.Length); 

내 생각이 바로 con.Close()pict.Length을 확인하는 것입니다 기본 코드와 실패하면, 나는 기본 이미지 또는 텍스트를 표시합니다.

그럴 수 있습니까? 방법?

+0

나는이 글 건너왔다,하지만 난 http://www.nullskull.com/a/263/aspnet-write-image-to-responseoutputstream.aspx – Chad

+0

내가 이것을 구현하기 위해 노력하고 따르지 않는 https://stackoverflow.com/a/2070493/3790921 그러나 "스트림"하는 방법을 알아낼 수 없습니다 – Chad

답변

0

DB에 이미지가없는 경우 디스크에서 이미지를로드하려면이 스 니펫을 사용하십시오.

public void ProcessRequest(HttpContext context) 
{ 
    //create a new byte array 
    byte[] pict = new byte[0]; 

    //create a connection to the db and a command 
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DataSource.iMIS.Connection"].ConnectionString)) 
    using (SqlCommand command = new SqlCommand("SELECT PICTURE_LOGO FROM Name_Picture WHERE ID = @EmpID", connection)) 
    { 
     //set the proper command type 
     command.CommandType = CommandType.Text; 

     //replace the parameters 
     command.Parameters.Add("@EmpID", SqlDbType.Int).Value = id; 

     try 
     { 
      //open the db and execute the sql string 
      connection.Open(); 
      pict = (byte[])command.ExecuteScalar(); 
     } 
     catch (Exception ex) 
     { 
      //catch any errors like unable to open db or errors in command. view with ex.Message 
     } 
    } 

    //if no image found in database load the default from disk 
    if (pict == null || pict.Length == 0) 
    { 
     pict = File.ReadAllBytes(context.Server.MapPath("/noimage.bmp")); 
    } 

    //clear the buffer stream 
    context.Response.ClearHeaders(); 
    context.Response.Clear(); 
    context.Response.Buffer = true; 

    //set the correct ContentType 
    context.Response.ContentType = "image/bmp"; 

    //set the filename for the image 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"ImageName.bmp\""); 

    //set the correct length of the string being send 
    context.Response.AddHeader("content-Length", pict.Length.ToString()); 

    //send the byte array to the browser 
    context.Response.OutputStream.Write(pict, 0, pict.Length); 

    //cleanup 
    context.Response.Flush(); 
    context.ApplicationInstance.CompleteRequest(); 
} 
+0

감사합니다! 이 줄은 여기'pict = File.ReadAllBytes (context.Server.MapPath ("/ noimage.bmp"));와 정확히 일치합니다. – Chad

0

많은 검색과 'HttpCompileException (s)'이 많이 발생하면이 작업이 수행됩니다.

덕분에 여기 답변을 @Kazar https://stackoverflow.com/a/2070493/3790921 및 @Pranay라나 나는 이것을 함께 넣어 여기이 대답 https://stackoverflow.com/a/3801289/3790921

을 위해 ...

 con.Open(); 
     byte[] pict = (byte[])cmd.ExecuteScalar(); 
     con.Close(); 

     ctx.Response.ContentType = "image/bmp"; 
     if (pict.Length <= 1) { 
      // the BLOB is not a picture 
      byte[] txt = ImageToByteArray(DrawText("no image found")); 
      ctx.Response.OutputStream.Write(txt, 0, txt.Length); 
     } else { 
      // stream the picture data from BLOB 
      ctx.Response.OutputStream.Write(pict, 0, pict.Length); 
     } 

를하며 노력하고 있습니다.

+0

이 접근법의 보너스는 출력 및 오류 메시지를 보내거나 텍스트/그림을 즉시 변경할 수 있다는 것입니다. – Chad