我试图在GridView中显示上传的图片,但是每次我想从数据库中获取数据并将字节数组再次解码为base64字符串时,我都会得到一个System.InvalidCastException
。它说对象System.String
无法转换为System.Byte[]
。
这是我到目前为止编写的方法:
数据库中的图像表:
CREATE TABLE [dbo].[epadoc_mod_wound_image] (
[image_id] INT IDENTITY (1, 1) NOT NULL,
[image_file] NVARCHAR (MAX) NULL,
[file_size] VARCHAR (50) NULL,
[image_format] VARCHAR (100) NULL,
[image_time] DATETIME NULL,
[wound_id] INT NULL,
PRIMARY KEY CLUSTERED ([image_id] ASC),
FOREIGN KEY ([wound_id]) REFERENCES [dbo].[epadoc_mod_wound_details] ([wound_id])
上传方法:
protected void btn_Upload_Click(object sender, EventArgs e)
{
try
{
// checks, if the uploaded picture either is a jpeg- or a png-file
if (uploadWoundPic.PostedFile.ContentType == "image/jpeg" | uploadWoundPic.PostedFile.ContentType == "image/png")
{
// read the image properties
string imageFormat = uploadWoundPic.PostedFile.ContentType;
int fileSize = uploadWoundPic.PostedFile.ContentLength;
string imageSize = fileSize.ToString();
DateTime imageTime = DateTime.Now;
// convert the image to Byte Array
byte[] bytes = new byte[fileSize];
HttpPostedFile img = uploadWoundPic.PostedFile;
img.InputStream.Read(bytes, 0, fileSize);
// saves the filename in a variable
string filename = Path.GetFileName(uploadWoundPic.PostedFile.FileName);
// convert the Byte Array to Base64 Encoded string
string imageFile = Convert.ToBase64String(bytes, 0, bytes.Length);
// save picture on server in given folder
_db.SaveWoundImage(imageFile, imageSize, imageFormat, imageTime);
}
}
catch (Exception)
{
}
}
那没有问题。
带有图像的GridView控件:
<asp:GridView ID="woundImageGridview" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="wound_id" HeaderText="ID_Wunde" SortExpression="File"></asp:BoundField>
<asp:BoundField DataField="image_file" HeaderText="Imagefile" SortExpression="File"></asp:BoundField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="woundimage" runat="server" ImageUrl='<%# "data:image/png;base64," + Convert.ToBase64String((byte[])Eval("image_file"))%>' Height="150px" Width="150px"></asp:Image>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
还有我从数据库中获取数据的方法:
private void BindData()
{
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["pflegedokumentationConnectionString"];
SqlConnection conn = new SqlConnection(connectionString.ConnectionString);
SqlCommand query = new SqlCommand("SELECT * FROM epadoc_mod_wound_image", conn);
conn.Open();
woundImageGridview.DataSource = query.ExecuteReader();
woundImageGridview.DataBind();
conn.Close();
}
但是每次我调用该方法时,例如在PageLoad或按钮上,单击“我得到此异常”。
答案 0 :(得分:2)
消息清晰
System.String无法转换为System.Byte []
在那个时候
<asp:Image ID="woundimage" runat="server" ImageUrl='<%# "data:image/png;base64,"
+ Convert.ToBase64String((byte[])Eval("image_file"))%>' Height="150px" Width="150px"></asp:Image>
Eval("image_file")
是一个字符串,而不是一个字节[],声明是字符串,保存到数据库中的是字符串-因此这是主要错误。