[ASP.NET] 上傳圖檔並顯示在網頁上

  • 12794
  • 0

摘要:[ASP.NET] 上傳圖檔並顯示在網頁上

最近小弟剛好遇到有個需求

USER需要上傳圖片,並且可以顯示在網頁上

但是,因為怕上傳圖片太多導致儲存位置爆掉

因此~小弟把圖片都在記憶體中處理,沒有實際存到Server電腦上

減少不必要的浪費,速度也比較快

不多說直接看CODE


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>上傳圖檔並顯示在網頁上</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="uploadFile" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="顯示圖片" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

protected void Button1_Click(object sender, EventArgs e)
        {
            //上傳圖檔並顯示在畫面上
            if (uploadFile.PostedFile != null)
            {
                // File was sent
                HttpPostedFile myFile = uploadFile.PostedFile;

                // Get size of uploaded file
                int nFileLen = myFile.ContentLength;

                // Allocate a buffer for reading of the file
                byte[] myData = new byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                Response.Clear();
                Response.ContentType = "image/jpeg";
                Response.BinaryWrite(myData);
            }
            else
            {
                // No file
            }
        }

 






Y2J's Life:http://kimenyeh.blogspot.tw/