2016-09-07 8 views
0

데이터베이스에 저장된 이미지를 표시해야하는 webapp의 서버 측 구성 요소를 작업 중입니다.byte []의 URL로 파일 제공

바이트 배열이나 스트림을 HTML img 태그의 유효한 URL로 변환하는 방법을 찾으려고합니다.

byte []에는 헤더를 포함한 전체 파일이 들어 있습니다.

해결책을 찾았지만 URL에서 파일 스트림으로 저장하는 것과 반대되는 문제를 계속 발견했습니다.

동적으로 생성되는 URL을 통해 파일을 제공하는 방법이 있습니까? 아니면 링크 할 파일의 실제 복사본을 만들어야합니까?

답변

0

바이트 배열을 Base64 이미지로 변환 할 수 있습니다.

public string getBase64Image(byte[] myImage) 
    { 
     if (myImage!= null) 
     { 
      return "data:image/jpeg;base64," + Convert.ToBase64String(myImage); 
     } 
     else 
     { 
      return string.Empty; 
     } 
    } 

이미지 태그는 다음과 같이 표시됩니다

또는 더 큰 이미지 (및 기타 파일 형식)은 다음과 같이됩니다 Generic Handler

public void ProcessRequest(HttpContext context) 
    { 
     //check if the querystring 'id' exists 
     if (context.Request.QueryString["id"] != null) 
     { 
      string idnr = context.Request.QueryString["id"].ToString(); 

      //check if the id falls withing length parameters 
      if (idnr.Length > 0 && idnr.Length < 40) 
      { 
       //get the data from the db or other source 
       byte[] bin = getMyDataFromDB(); 

       //clear the headers 
       context.Response.ClearHeaders(); 
       context.Response.ClearContent(); 
       context.Response.Clear(); 
       context.Response.Buffer = true; 

       //if you do not want the images to be cached by the browser remove these 3 lines 
       context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1)); 
       context.Response.Cache.SetCacheability(HttpCacheability.Public); 
       context.Response.Cache.SetValidUntilExpires(false); 

       //set the content type and headers 
       context.Response.ContentType = "image/jpeg"; 
       context.Response.AddHeader("Content-Disposition", "attachment; filename=\"myImage.jpg\""); 
       context.Response.AddHeader("content-Length", bin.Length.ToString()); 

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

       //cleanup 
       context.Response.Flush(); 
       context.Response.Close(); 
       context.Response.End(); 
      } 
     } 
    } 

이미지 태그를 사용하는 것이 좋습니다에 대한 <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgA..."> : <img src="/Handler1.ashx?id=AB-1234">

+0

실제로 이미지 자체를 src 태그에 포함시킬 수 있는지 전혀 몰랐습니다! 나는 이것을 바로 시도 할 것이다. – rxj

+2

Base64로 변환하면 큰 문자열이 생성됩니다. 나는 보통 50 kb 이상의 이미지를 가진 첫 번째 방법을 사용하지 않는다. – VDWWD

+0

@VDWWD ashx 처리기를 만들 필요가 없습니다. 코드 제공 이미지를 바이트 [] (두 번째 해법)로 처리하면 "일반"getimage.aspx 페이지의 Page_Load()에서 작동합니다. 단지'context.'를'this로 대체하십시오. '(또는 아무것도) –