c# - Serve file in byte[] as URL -


i working on serverside component of webapp should display images stored in database.

i trying find way transform byte array or stream valid url html img tag.

the byte[] contains entire file including headers.

i have searched solution kept finding reverse problem of saving filestream url.

is there way serve file via kind of dynamically generated url or have create physical copy of file link to?

you can convert byte array base64 image.

    public string getbase64image(byte[] myimage)     {         if (myimage!= null)         {             return "data:image/jpeg;base64," + convert.tobase64string(myimage);         }         else         {             return string.empty;         }     } 

your image tag this: <img src="data:image/jpeg;base64,/9j/4aaqskzjrga...">

or larger images (and other file types) it's better use generic handler

    public void processrequest(httpcontext context)     {         //check if querystring 'id' exists         if (context.request.querystring["id"] != null)         {             string idnr = context.request.querystring["id"].tostring();              //check if id falls withing length parameters             if (idnr.length > 0 && idnr.length < 40)             {                 //get data db or other source                 byte[] bin = getmydatafromdb();                  //clear headers                 context.response.clearheaders();                 context.response.clearcontent();                 context.response.clear();                 context.response.buffer = true;                  //if not want images cached 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 content type , headers                 context.response.contenttype = "image/jpeg";                 context.response.addheader("content-disposition", "attachment; filename=\"myimage.jpg\"");                 context.response.addheader("content-length", bin.length.tostring());                  //write byte array                 context.response.outputstream.write(bin, 0, bin.length);                  //cleanup                 context.response.flush();                 context.response.close();                 context.response.end();             }         }     } 

your image tag this: <img src="/handler1.ashx?id=ab-1234">


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -