R. Jaška R. Jaška - 1 year ago 180
ASP.NET (C#) Question

Serve file in byte[] as URL

I am working on a serverside component of a webapp which should display images stored in database.

I am trying to find a way to transform a byte array or a stream to a valid URL for the HTML img tag.

The byte[] contains the entire file including headers.

I have searched for a solution but I kept finding the reverse problem of saving to filestream from a url.

Is there a way to serve the file via some kind of a dynamically generated url or do I have to create a physical copy of the file to link to?

Answer Source

You can convert the Byte Array to a Base64 image.

    public string getBase64Image(byte[] myImage)
        if (myImage!= null)
            return "data:image/jpeg;base64," + Convert.ToBase64String(myImage);
            return string.Empty;

Your image tag will look like this: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgA...">

Or for larger images (and other file types) it's better to use a 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.Buffer = true;

                //if you do not want the images to be cached by the browser remove these 3 lines

                //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);


Your image tag will look like this: <img src="/Handler1.ashx?id=AB-1234">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download