2012-07-10 153 views
2

我需要從數據庫中顯示圖像的幫助。我讀過使用處理程序將圖像從數據庫加載到處理程序的效率。但我不想使用處理程序,因爲我認爲將imageUrl設置爲處理程序時,圖像只會在pageLoad上加載。在我的情況下,我有一個現有的圖像出現在我的img標籤上,然後上傳後,我需要更改該圖像。我使用了ajaxFileUploader插件併成功上傳並將圖像保存到數據庫。我現在的問題是檢索它。顯示從數據庫檢索圖像到圖像控制

在成功的jquery ajax調用,我將使用Ajax來調用一個WebMethod。這裏是我的代碼:

$.ajaxFileUpload 
(
    { 
     url: 'AjaxFileUploader.ashx', 
     secureuri: false, 
     fileElementId: 'uploadControl', 
     dataType: 'json', 
     data: '{}', 
     success: function() { 
      $.ajax({ 

       type: "POST", 

       url: "UserProfile.aspx/displayImage", 

       data: jsonData, 

       contentType: "application/json; charset=utf-8", 

       dataType: "json", 

       success: function (mydata) { 
       } 
      }); 
     }, 
     error: function() { 

     } 
    } 
) 

在我的圖像檢索,下面的代碼是否存在:

public void ProcessRequest(HttpContext context) 
    { 
    string userid = context.Request.QueryString["user"]; 
     DBAccess dbacc = new DBAccess(); 
     DataTable dt = dbacc.getImage(userid); 
     byte[] image = ((byte[])dt.Rows[0]["UserImage"]); 
     System.Drawing.Image img = byteArrayToImage(image); 

     MemoryStream stream = new MemoryStream(); 
     img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
     img.Dispose(); 
     stream.Position = 0; 
     byte[] data = new byte[stream.Length]; 
     stream.Read(data, 0, (int)stream.Length); 
     stream.Dispose(); 
     context.Response.Clear(); 
     context.Response.ContentType = "image/jpeg"; 
     context.Response.BinaryWrite(data); 
} 

我字節到圖像轉換:

public Image byteArrayToImage(byte[] byteArrayIn) 
    { 
     MemoryStream ms = new MemoryStream(byteArrayIn); 
     Image returnImage = Image.FromStream(ms); 
     return returnImage; 
    } 

我的數據庫訪問:

public DataTable getImage(string userid) 
    { 
     DataTable dtGetImage = new DataTable(); 

     using (SqlConnection cn = MySqlDataAccess.sqlDataAccess.MySqlConnection()) 
     { 
      using (SqlCommand cmd = MySqlDataAccess.sqlDataAccess.MySqlCommand(cn, CommandType.Text, "SELECT * FROM Images WHERE UserId = @userid")) 
      { 
       cmd.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid; 

       using (SqlDataAdapter da = MySqlDataAccess.sqlDataAccess.MySqlAdapter(cmd)) 
       { 
        da.Fill(dtGetImage); 
       } 
      } 
     } 

     return dtGetImage; 
    } 

FileUploader.ash x代碼:

public void ProcessRequest(HttpContext context) 
    { 
     string path = context.Server.MapPath("~/Temp"); 
      if (!Directory.Exists(path)) 
       Directory.CreateDirectory(path); 

      var file = context.Request.Files[0]; 

      string userid = context.Request.QueryString["user"]; 

      string fileName; 

      if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") 
      { 
       string[] files = file.FileName.Split(new char[] { '\\' }); 
       fileName = files[files.Length - 1]; 
      } 
      else 
      { 
       fileName = file.FileName; 
      } 
      string fileType = file.ContentType; 
      string strFileName = fileName; 

      int filelength = file.ContentLength; 
      byte[] imagebytes = new byte[filelength]; 
      file.InputStream.Read(imagebytes, 0, filelength); 
      DBAccess dbacc = new DBAccess(); 
      dbacc.saveImage(imagebytes, userid); 

      var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
      var result = new { name = file.FileName }; 
      context.Response.Write(serializer.Serialize(result)); 
    } 

請幫忙!謝謝!

+0

我會在這裏開始評論,因爲我的回答評論日誌變得這麼長。讓我們假裝http://localhost/ImageRetrieval.ashx?user = ljpv14返回你的圖片。如果您將瀏覽器指向該URL,並將響應保存爲test.jpg,您是否可以在圖像查看器/編輯器中打開該文件? – 2012-07-11 14:12:40

+0

沒有。我無法打開文件。 – ljpv14 2012-07-11 14:20:23

+0

修改了包含可能的處理程序修復程序的答案 – 2012-07-11 14:32:26

回答

2

你有一些體面的一般想法,但整體結構是缺乏的。你最好的選擇是使用use a handler,但在你的成功函數中引用處理函數。例如:

var userId = 'MyUserIdFromSomewhere'; 
$.ajaxFileUpload 
(
    { 
     url: 'AjaxFileUploader.ashx', 
     secureuri: false, 
     fileElementId: 'uploadControl', 
     dataType: 'json', 
     data: '{}', 
     success: function() { 
      $('.ImageId').attr('src', '/ImageRetrieval.ashx?user=' + userId); 
     }, 
     error: function() { 

     } 
    } 
) 

您可能需要修改您的處理程序看起來更像:

using System; 
using System.Web; 
using System.Configuration; 
using System.IO; 
using System.Data; 
using System.Data.SqlClient; 

public class DisplayImg : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     Int32 userId; 
     if (context.Request.QueryString["userId"] != null) 
      userId = Convert.ToInt32(context.Request.QueryString["userId"]); 
     else 
      throw new ArgumentException("No parameter specified"); 

     context.Response.ContentType = "image/jpeg"; 
     Stream strm = getImage(userId); 
     byte[] buffer = new byte[2048]; 
     int byteSeq = strm.Read(buffer, 0, 2048); 
     //Test File output. IIS_USR *SHOULD* have write access to this path, but if not you may have to grant it 
     FileStream fso = new FileStream(Path.Combine(Request.PhysicalApplicationPath, "test.jpg"), FileMode.Create); 

     while (byteSeq > 0) 
     { 
      fso.Write(buffer, 0, byteSeq); 
      context.Response.OutputStream.Write(buffer, 0, byteSeq); 
      byteSeq = strm.Read(buffer, 0, 2048); 
     } 

     fso.Close(); 
    } 

    public Stream getImage(string userid) 
    { 

     using (SqlConnection cn = MySqlDataAccess.sqlDataAccess.MySqlConnection()) 
     { 
      using (SqlCommand cmd = MySqlDataAccess.sqlDataAccess.MySqlCommand(cn, CommandType.Text, "SELECT UserImage FROM Images WHERE UserId = @userid")) 
      { 
       cmd.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid; 

       object theImg = cmd.ExecuteScalar(); 

       try 
       { 
        return new MemoryStream((byte[])theImg); 
       } 
       catch 
       { 
        return null; 
       } 
      } 
     } 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

這有可能是DataAdapter的是編碼/不正確地解釋數據blob和破壞你的形象。

+0

感謝您的提示。我清楚地忘記了.attr。另一個問題,我如何從處理程序的url訪問userId?我應該只使用請求查詢字符串嗎? – ljpv14 2012-07-10 21:37:59

+0

這將是最簡單的方法,假設您不關心安全性/某人訪問其他人的圖像。 – 2012-07-10 21:49:53

+0

如果我關心安全性,該怎麼辦?我認爲是時候考慮到安全問題了。 – ljpv14 2012-07-11 05:01:11