我想在我的网页上显示图像,同时点击应下载的链接按钮。存储的图像文件以二进制格式存储在db中。将base64字符串转换为图像时显示错误。详情如下。帮我找一个合适的解决方案。谢谢。
错误:
代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pdfDataSetTableAdapters.tbl_imgTableAdapter td;
td = new pdfDataSetTableAdapters.tbl_imgTableAdapter();
DataTable dt = new DataTable();
dt = td.GetId();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Id";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select Id--", ""));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
pdfDataSetTableAdapters.tbl_imgTableAdapter td;
td = new pdfDataSetTableAdapters.tbl_imgTableAdapter();
DataTable dt = new DataTable();
dt = td.GetImg(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
byte[] img2 = (byte[])row["img"];
string base2 = Convert.ToBase64String(img2);
Image1.ImageUrl = "data:image/jpg;base64," + base2;
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string sFile = Image1.ImageUrl;
if (string.IsNullOrEmpty(sFile))
{
return;
}
FileInfo fi = new FileInfo(Server.MapPath(sFile)); // error popup here
if (!fi.Exists)
{
return;
}
if (!string.IsNullOrEmpty(sFile))
{
// check if the file is an image
NameValueCollection imageExtensions = new NameValueCollection();
imageExtensions.Add(".jpg", "image/jpeg");
imageExtensions.Add(".gif", "image/gif");
imageExtensions.Add(".png", "image/png");
if (imageExtensions.AllKeys.Contains(fi.Extension))
{
Response.ContentType = imageExtensions.Get(fi.Extension);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fi.Name);
Response.TransmitFile(fi.FullName);
Response.End();
}
Response.Redirect(sFile);
}
.aspx的:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"> </asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Show" />
<asp:LinkButton ID="LinkButton1" runat="server">Download</asp:LinkButton>
<asp:Image ID="Image1" runat="server" />
Sql query1:
SELECT Id FROM tbl_img
Sql query1:
SELECT img FROM tbl_img WHERE (Id = @Id)
DB:
O / P屏幕:
答案 0 :(得分:0)
当用户单击“下载”链接时,您尝试打开Image1.URL,这是一个dataURL,而不是实际路径。这会导致MapPath失败。
Image1.URL是dataURL的原因是当您单击按钮1(显示)时将图像设置为dataurl。
您可以做的是将dataURL解析为文件并发送
protected void LinkButton1_Click(object sender, EventArgs e){
var data = Image1.ImageUrl.split('base64,')[1];
File f = Parse.File("filename.jpg", {"base64": data});
Response.Clear();
Response.ContentType = "image/jpg";
Response.WriteFile(f);
Response.Flush();
Response.End();
}