我需要帮助来显示数据库中的图像。我读过使用处理程序将图像从数据库加载到处理程序是有效的。但我不想使用处理程序,因为我假设当您将 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 () {
}
}
)
在我的 ImageRetrieval 中,存在以下代码:
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.ashx 代码:
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));
}
请帮忙!谢谢!