2017-02-08 28 views
0

imagehandler.ashx 이미지가 Chrome 브라우저에 표시되지 않습니다. 어떻게 해결할 수 있습니까 ..?imagehandler.ashx 이미지가 크롬에 표시되지 않습니다.

내 코드 (imagehandler.ashx는) :

public void ProcessRequest(HttpContext context) 
{ 
    if (context.Request.QueryString["YazarID"] != null) 
    { 
     string YazarID = context.Request.QueryString["YazarID"]; 
     DataTable dt = new DataTable(); 
     string query = "select img from Register where YazarID='" + YazarID + "'"; 
     dt = Database.GetData(query); 

     HttpResponse r = context.Response; 
     r.WriteFile("../Pictures/300/" + dt.Rows[0]["img"]); 
     HttpContext.Current.ApplicationInstance.CompleteRequest(); 
     context.Response.Flush(); 
     context.Response.Close(); 
     context.Response.End(); 
    } 
} 

이미지는 크롬 브라우저에서이처럼 보이는;

Screenshot an image in Chrome

답변

2

당신은 content-Length를 전송하지 않습니다. Chrome에서 이미지 (및 기타 파일)를 엉망으로 만들 수 있습니다. 물론 파일이 데이터베이스에 올바르게 저장되었다고 가정합니다.

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

    //get the item from a datatable 
    bin = (byte[])dt.Rows[0]["img"]; 

    //read the image in an `Image` and then get the bytes in a memorystream 
    Image img = Image.FromFile(context.Server.MapPath("test.jpg")); 
    using (var ms = new MemoryStream()) 
    { 
     img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
     bin = ms.ToArray(); 
    } 

    //or as one-liner 
    bin = File.ReadAllBytes(context.Server.MapPath("test.jpg")); 

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

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

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

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

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

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

감사합니다. VDWWD. 그러나 내 이미지는 DB에 저장되지 않습니다. 이미지 경로 만 DB에 있습니다. 실제 이미지는 "../Pictures/300/"디렉토리 아래에 있습니다. 이 상황을 어떻게 처리 할 수 ​​있습니까? –

+0

답변을 업데이트했습니다. – VDWWD

+0

다시 한번 고마워요. 이 진술을 삭제하고 올바르게 작동했습니다. bin = (byte []) dt.Rows [0] [ "img"]; –