从数据库中检索到的图像控制显示图像
我需要从数据库中显示图像的帮助。我读过,这是有效地使用处理程序从数据库加载图像处理程序。但我不希望因为我认为,当你的图片网址设置为一个处理器,图像将只在页面加载加载使用处理程序。就我而言,我有一个现有的图像present我的img标签,然后上传后,我需要改变这种形象。我用ajaxFileUploader插件,并上传成功以及图像保存到数据库中。我现在的问题是它检索
I need help in displaying an image from database. I've read that it's efficient to use handlers to load image from database to a handler. But I don't want to use handlers because I assumed that when you set the imageUrl to a handler, the image will only be loaded upon pageLoad. In my case, I have a existing image present at my img tag, then after uploading, I need to change that image. I used ajaxFileUploader plugin and successfully uploaded and save the image to the database. My problem now is retrieving it.
在成功的jquery ajax调用,我将使用AJAX调用一个WebMethod。这里是我的code为:
upon successful jquery ajax call, I will be calling a webmethod using ajax. Here is my code for that:
$.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 () {
}
}
)
在我ImageRetrieval,下面codeS是present:
In my ImageRetrieval, the following codes are present:
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);
}
我要字节图像转换:
My Byte to Image conversion:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
我的数据库访问:
My database access:
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.ashx code:
FileUploader.ashx code:
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));
}
请帮助!谢谢!
您有一些体面的总体思路,但缺乏整体结构。最好的办法是使用使用处理,但在你的成功函数引用的处理程序。例如:
You have some decent general ideas, but the overall structure is lacking. Your best bet is to use a use a handler, but reference the handler in your success function. Example:
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 () {
}
}
)
您可能需要修改你的处理器看起来更像是:
You may want to modify your handler to look more like:
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的是编码/间$ P $错误pting数据BLOB和破坏你的形象。
It's possible that the DataAdapter is encoding/interpreting the data blob incorrectly and corrupting your image.