`
yeak2001
  • 浏览: 101216 次
  • 性别: Icon_minigender_1
  • 来自: 无锡
社区版块
存档分类
最新评论

Use IO Stream Response image

阅读更多
  最近的一个项目分成web site和 admin site2个站点.然后就遇到一个web下new sign permit,然后到admin下审批的问题.问题的关键在于web下的那个功能有个上传文件的功能.文件可能是image,也可以是doc,pdf,如果是image就需要display.
  问题在于2个站点并不能共享upload目录,也就是web上传的,admin并不能访问.查询了相关资料以后有以下几个解决方案:
1.存数据库2进制流,读取都方便
2.存IO stream, 存在服务器physical path,这样就不用care共享的问题了,2边都往同一个目录下upload.

第2个方法就有个读取显示图片的问题.不在server控制的目录下如何显示图片呢.显然不能简单的<image src="xxx.img" />,不可能简单的把物理路径写在image标签里,到了客户端根本没办法解析.这里就得用IO stream把图片取成 byte,然后response到一个单独的页面上
step1:
create empty page, in the page write init function

private void createImage(String imagePath)
    {
        if (imagePath != null && imagePath != String.Empty)
        {
            Response.ContentType = "image/jpeg";
            byte[] bytes = null;
            Stream stream = null;
            try
            {
                stream = new FileStream(imagePath, FileMode.Open);
                using (MemoryStream ms = new MemoryStream())
                {
                    int b;
                    while ((b = stream.ReadByte()) != -1)
                    {
                        ms.WriteByte((byte)b);
                    }
                    bytes = ms.ToArray();
                }

                Response.BinaryWrite(bytes);
                Response.Flush();
            }
            catch (Exception ex)
            {
                bytes = null;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }
    }

这样就可以产生一个显示图片的页面
step 2: 把这个页面的url放到<image src="viewImage.aspx?"imagePath="xxx" />
这样就可以显示图片了.

另外download也可以用上面的strem做,只需要加上
 Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = type;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics