这是我的数据库:
create table images
(
ID int primary key identity,
Name nvarchar(255),
Size int,
ImgData varbinary(max)
)
CREATE PROCEDURE UploadImages
@Name nvarchar(255),
@Size int,
@ImgData varbinary(max),
@NewId int output
AS
BEGIN
INSERT INTO images
VALUES (@Name, @Size, @ImgData)
SELECT @NewId = SCOPE_IDENTITY()
END
我想将数据库中的图像显示到标签中 - 我该如何在asp.net中执行此操作?
这是我的代码:
HttpPostedFile PostedFile = FileUpload1.PostedFile;
string fileName = Path.GetFileName(PostedFile.FileName);
string fileExtension = Path.GetExtension(fileName);
int fileSize = PostedFile.ContentLength;
if(fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".bmp"|| fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
{
Stream stream = PostedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("UploadImages", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter paramName = new SqlParameter()
{
ParameterName = "@Name",
Value = fileName
};
cmd.Parameters.Add(paramName);
SqlParameter paramSize = new SqlParameter()
{
ParameterName = "@Size",
Value = fileSize
};
cmd.Parameters.Add(paramSize);
SqlParameter paramImgData = new SqlParameter()
{
ParameterName = "@ImgData",
Value = bytes
};
cmd.Parameters.Add(paramImgData);
SqlParameter paramNewId = new SqlParameter()
{
ParameterName = "@NewId",
Value =-1,
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(paramNewId);
cmd.ExecuteNonQuery();
con.Close();
Lmas.Visible = true;
Lmas.Text = "done";
Lmas.ForeColor = System.Drawing.Color.Green;
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = "~/ShowImage.aspx?Id=" + cmd.Parameters["@NewId"].Value.ToString();
//LoadImage();
}
}
else
{
Lmas.Visible = true;
Lmas.Text = "only images (.jpg .png .gif .bmp) can be uploaded";
Lmas.ForeColor = System.Drawing.Color.Red;
HyperLink1.Visible = false;
}
答案 0 :(得分:0)
一个简单的解决方法是:
<img id="img" runat="server" alt=""/> (instead of an label)
并在您的函数中
img.Src = "data:image/jpg;base64," + Convert.ToBase64String((byte[])datarow[0]);