[ASP.NET] 在頁面上顯示上傳的圖片

  • 34199
  • 0

摘要:[ASP.NET] 在頁面上顯示上傳的圖片

這幾天同事剛好遇到一個問題

想要讀取圖片並顯示在頁面上

因此小弟做了一個範例

順便做個紀錄

 


#前台程式碼...建立上傳檔案頁面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="A3.aspx.cs" Inherits="A3" %>

<!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 runat="server" ID="filMyFile" />
        <asp:Button Text="Click" ID="btn_Go" UseSubmitBehavior="false" runat="server" OnClick="btn_Go_Click" />
        <br />
        <asp:Image runat="server" ID="img" />
    </div>
    </form>
</body>
</html>

 

 


// 後台程式碼

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class A3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_Go_Click(object sender, EventArgs e)
    {
        if (filMyFile.PostedFile != null)
        {
            ////1. 圖片直接顯示在本頁面上
            //// File was sent
            //HttpPostedFile myFile = filMyFile.PostedFile;

            //// 抓取上傳檔案的大小
            //int nFileLen = myFile.ContentLength;

            //// 設定buffer大小
            //byte[] myData = new byte[nFileLen];
            //myFile.InputStream.Read(myData, 0, nFileLen);
            //Response.Clear();
            //Response.ContentType = "image/jpeg";
            //Response.BinaryWrite(myData);

            //2. 圖片顯示在IMAGE的控件上
            // File was sent
            HttpPostedFile myFile = filMyFile.PostedFile;

            Session["myFile"] = myFile;

            // Set ImageUrl
            img.ImageUrl = "showImage.ashx";
        }
    }
}

 

 


// 建立showImage.ashx

<%@ WebHandler Language="C#" Class="showImage" %>

using System;
using System.Web;
using System.Web.SessionState;

public class showImage : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");

        if (context.Session["myFile"] != null)
        {
            HttpPostedFile myFile = (HttpPostedFile)context.Session["myFile"];
            int nFileLen = myFile.ContentLength;
            // Allocate a buffer for reading of the file

            byte[] myData = new byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);
            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(myData);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

 






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