1. 程式人生 > >ASP.NET學習筆記(二)——一般處理程式之圖片上傳

ASP.NET學習筆記(二)——一般處理程式之圖片上傳

簡單圖片上傳功能

  • 目標:實現從本地磁碟讀取圖片檔案,展示到瀏覽器頁面。
  • 步驟:

(1). 首先建立一個用於上傳圖片的HTML模板,命名為ImageUpload.html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />    
</head>
<body
>
<!--檔案上傳必須設定enctype="multipart/form-data"--> <form method="post" enctype="multipart/form-data" action="ImageUpload.ashx"> <input type="file" name="imgFile" /> <input type="submit" value="上傳"/> </form> </body> </html>

模板中包含兩個input標籤,型別分別為“file”和“submit”,其中,form表單的method屬性必須為“post”,enctype為“multipart/form-data”。

(2). 在ImageUpload.html模板中判斷一下所上傳的檔案是否為圖片:

<script src="../scripts/jquery-1.12.4.min.js"></script>
    <!--如果監聽到上傳的檔案的字尾不是圖片,那就將file得到的內容設為空-->
    <script type="text/javascript">
        $(function () {
            $(":file").change(function () {
                var fileName = $(this
).val(); var ext = fileName.substr(fileName.lastIndexOf('.')); if (ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".gif") { return true; } else { $(this).val(""); } }); });
</script>

(3). 新建一個名為ImageUpload.ashx的一般處理程式,為保證上傳的檔案是圖片,需要在後臺再次判斷一下所傳檔案的格式(因為瀏覽器中可以改前臺程式碼):

using System;
using System.IO;
using System.Web;

namespace ThreeLayerWebDemo.FileUpload
{
    /// <summary>
    /// ImageUpload 的摘要說明
    /// </summary>
    public class ImageUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //context.Response.Write("Hello World");
            //後臺拿到上傳來的圖片(拿到名為imgFile的input標籤的檔案)
            var file =context.Request.Files["imgFile"];

            //後臺也要對拿到的資料是否為圖片進行校驗(因為前臺可以通過瀏覽器改程式碼,前臺校驗完了需要後臺再攔截一下)
            var ext=  Path.GetExtension(file.FileName);
            if (!(ext==".jpeg"||ext==".jpg"||ext==".png"||ext==".gif"))
            {
                context.Response.Write("shit,你傳的不是圖片");
                context.Response.End();
            }
            else
            {
                //上傳的檔案儲存到目錄(為了保證檔名不重複,加個Guid)
                string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
                file.SaveAs(context.Request.MapPath(path));//必須得是相對路徑

                //把圖片顯示到前端讓使用者看得到
                string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>",
                    path);//必須得是絕對路徑!!!!
                context.Response.Write(str);
            }



        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}