以byte []形式提供文件作为URL
问题描述:
我正在开发一个Web应用程序的服务器端组件,它应显示存储在数据库中的图像。以byte []形式提供文件作为URL
我想找到一种方法来将字节数组或流转换为HTML img标记的有效URL。
byte []包含整个文件,包括标题。
我已经搜索了一个解决方案,但我仍然发现从URL保存到文件流的逆向问题。
有没有办法通过某种动态生成的url来提供文件,或者我是否需要创建要链接到的文件的物理副本?
答
您可以将字节数组转换为Base64图像。
public string getBase64Image(byte[] myImage)
{
if (myImage!= null)
{
return "data:image/jpeg;base64," + Convert.ToBase64String(myImage);
}
else
{
return string.Empty;
}
}
您的图像标记看起来像这样:<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgA...">
或为大型图像(和其他文件类型),最好使用Generic Handler
public void ProcessRequest(HttpContext context)
{
//check if the querystring 'id' exists
if (context.Request.QueryString["id"] != null)
{
string idnr = context.Request.QueryString["id"].ToString();
//check if the id falls withing length parameters
if (idnr.Length > 0 && idnr.Length < 40)
{
//get the data from the db or other source
byte[] bin = getMyDataFromDB();
//clear the headers
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.Clear();
context.Response.Buffer = true;
//if you do not want the images to be cached by the browser remove these 3 lines
context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetValidUntilExpires(false);
//set the content type and headers
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"myImage.jpg\"");
context.Response.AddHeader("content-Length", bin.Length.ToString());
//write the byte array
context.Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
context.Response.Flush();
context.Response.Close();
context.Response.End();
}
}
}
您的图像标记看起来像这样:<img src="/Handler1.ashx?id=AB-1234">
我不知道你实际上可以将图像本身嵌入到src标记中! 我会马上试试。 – rxj
请注意,转换为Base64将创建一个大字符串。我通常不使用图像大于50 kb的第一种方法。 – VDWWD
@VDWWD不需要创建一个ashx处理程序:将图像作为byte [](第二种解决方案)提供的代码将在“normal”getimage.aspx页面的Page_Load()中工作 - 只需将'context.'替换为'this。 '(或没有) –