简体   繁体   English

如何 stream 字节数组图像?

[英]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.出于某种奇怪的原因,通过 IE6 使用的一个使用了五年的内部asp.net web 应用程序突然出现了一个问题,即使没有代码更改。 Certain images that are being streamed back to the web browser aren't appearing for some users.某些用户不会显示正在流回 web 浏览器的某些图像。

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.我不知道为什么突然开始发生这种情况或原因是什么 - 但是作为搜索的一部分,我正在考虑用于 stream 背面图像的代码是否存在缺陷。

The image is held in memory are a byte array, then streamed back using the following code.图像保存在 memory 中,是一个字节数组,然后使用以下代码流回。 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":
        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)如果我尝试在它自己的 window 中打开图像,我会看到图像或大量 gobbledygook 文本(我猜这意味着浏览器没有设置/拾取 MIME 类型)

Response.End() is generally bad as it aborts the IIS thread even if it's in the middle of Flush()-ing. Response.End()通常很糟糕,因为它会中止 IIS 线程,即使它处于 Flush() 的中间。

Use Response.Flush() followed by Response.Close() to make sure all content is sent to the client.使用Response.Flush()后跟Response.Close()确保所有内容都发送到客户端。

I could be wrong about this one but i think the Content-Length should contain the length of the body in bytes.我可能错了,但我认为Content-Length应该包含正文的长度(以字节为单位)。 Response.BinaryWrite will base64 encode the data wich will be longer then the byte[] length you are telling it is in the header. Response.BinaryWrite将 base64 对数据进行编码,该数据将比您告诉它在 header 中的byte[]长度更长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM