Use IO Stream Response image


最近のプロジェクトはweb siteとadmin siteの2つのサイトに分かれている.それから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つ目の方法は、表示画像を読み取る問題がある.サーバ制御されていないディレクトリの下でどのように画像を表示しますか?明らかに簡単なことができなくて、簡単に物理の経路を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を
これで画像を表示できます.
またdownloadは上のstremでもできますが、追加するだけです

 Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = type;