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

本文关键字:URL 提供 文件 字节 | 更新日期: 2023-09-27 18:06:12

我正在一个web应用程序的服务器端组件,应该显示存储在数据库中的图像。

我正试图找到一种方法来转换字节数组或流为HTML img标签的有效URL。

字节[]包含整个文件,包括头文件。

我已经寻找了一个解决方案,但我一直发现从url保存到文件流的反向问题。

是否有一种方法可以通过某种动态生成的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...">

或者对于较大的图像(和其他文件类型),最好使用通用处理程序
    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">