2012-07-10 115 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