将byte []中的文件作为URL提供

时间:2016-09-07 11:17:32

标签: c# asp.net url server bytearray

我正在研究webapp的服务器端组件,它应该显示存储在数据库中的图像。

我正在尝试找到一种方法将字节数组或流转换为HTML img标记的有效URL。

byte []包含整个文件,包括标题。

我搜索了一个解决方案,但我一直在寻找从网址保存到文件流的相反问题。

有没有办法通过某种动态生成的URL来提供文件,还是我必须创建要链接到的文件的物理副本?

1 个答案:

答案 0 :(得分:0)

您可以将字节数组转换为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">

相关问题