How to stream byte array image?
For some strange reason, a five year old internal asp.net web app that is used through IE6 has suddenly developed an issue, even though there have been no code changes. Certain images that are being streamed back to the web browser aren't appearing for some users.
I don't know why this was suddenly started happening or what the cause is - however as part of the search, I'm considering if there's a flaw in the code used to stream back images.
The image is held in memory are a byte array, then streamed back using the following code. Is this the best way to stream an image back?
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
// Work out file type
switch( Path.GetExtension( imageFilename ).ToLower() )
{
case ".jpg":
case ".jpeg":
Response.ContentType = "image/jpeg";
break;
case ".gif":
开发者_Python百科 Response.ContentType = "image/gif";
break;
default:
Response.ContentType = "binary/octet-stream";
break;
}
Response.AddHeader("Content-Length", imageBytes.Length.ToString() );
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite( imageBytes );
Response.End();
Instead of an image being shown in the page, a red cross is displayed. This only happens with the dynamically generated images shown on the page, rather than the statically linked images.
If I try and open the image in it's own window, I either see the image or a load of gobbledygook text (Which I'm guessing means the MIME type isn't being set/picked up by the browser)
Response.End()
is generally bad as it aborts the IIS thread even if it's in the middle of Flush()-ing.
Use Response.Flush()
followed by Response.Close()
to make sure all content is sent to the client.
I could be wrong about this one but i think the Content-Length
should contain the length of the body in bytes. Response.BinaryWrite
will base64 encode the data wich will be longer then the byte[]
length you are telling it is in the header.
精彩评论