gpt4 book ai didi

jquery - 将从数据库检索到的图像显示到图像控件

转载 作者:行者123 更新时间:2023-12-01 04:20:09 27 4
gpt4 key购买 nike

我需要帮助来显示数据库中的图像。我读到使用处理程序将图像从数据库加载到处理程序是有效的。但我不想使用处理程序,因为我假设当您将 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));
}

请帮忙!谢谢!

最佳答案

你有一些不错的总体想法,但缺乏整体结构。你最好的选择是使用 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 并损坏您的图像。

关于jquery - 将从数据库检索到的图像显示到图像控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11419345/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com