首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 2.0 無刷新圖片上傳並即時顯示縮圖

     編輯:ASP.NET 基礎

使用 jQuery Form Plugin 配合 Generic Handler (.ashx) 實現無刷新(AJAX)檔案上傳,上傳完成即時回顯縮圖。相容 IE、Firefox、Chrome 等主流瀏覽器。

前置準備

  • 引用 jquery.min.js
  • 引用 jquery.form.min.js(支援 ajaxSubmit)

前端頁面

<asp:FileUpload ID="Up_load" runat="server" onchange="upload()" />
<img id="server_img" width="360px" style="border:1px solid #ccc; padding:2px;" alt="預覽圖" />

<script type="text/javascript">
function upload() {
    var options = {
        type: "POST",
        url: '../Include/Files.ashx', // Generic Handler 路徑
        success: function (msg) {
            // msg 為伺服器回傳的圖片相對路徑
            $("#server_img").attr("src", msg);
        },
        error: function (xhr, status, err) {
            alert("上傳失敗:" + err);
        }
    };
    // 將表單提交轉為 AJAX
    $('#aspnetForm').ajaxSubmit(options);
}
</script>
  • onchange 觸發上傳,使用者選檔即自動送出。
  • $('#aspnetForm') 為 ASP.NET 頁面預設的 <form runat="server"> ID。

Generic Handler (Files.ashx)

public class Files : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpFileCollection files = context.Request.Files;
        if (files.Count > 0)
        {
            string savePath = "";
            Random rnd = new Random();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                if (file.ContentLength > 0)
                {
                    string ext = Path.GetExtension(file.FileName);
                    int rndNum = rnd.Next(5000, 10000);
                    // 相對網站根目錄的虛擬路徑
                    string virtualPath = "../../UserFiles/temp/" + rndNum + ext;
                    string physicalPath = context.Server.MapPath(virtualPath);

                    // 確保目錄存在
                    Directory.CreateDirectory(Path.GetDirectoryName(physicalPath));

                    file.SaveAs(physicalPath);
                    savePath = virtualPath; // 回傳最後一個檔案路徑
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(savePath);
        }
    }

    public bool IsReusable => false;
}

關鍵點總結

  • 路徑處理:Handler 使用 context.Server.MapPath 將虛擬路徑轉實體路徑儲存,回傳虛擬路徑供前端 img.src 使用。
  • 檔名衝突:範例用隨機數,正式環境建議 Guid.NewGuid() + 原始副檔名,或依上傳者 ID + 時間戳命名。
  • 安全性:必須驗證副檔名、Content-Type、檔案簽名(Magic Bytes),限制允許類型(.jpg/.png/.gif),防止上傳惡意腳本。
  • 目錄權限:UserFiles/temp 需給 IIS AppPool 身分寫入權限,但不可執行腳本(IIS 設定 Handler Mapping 移除 .aspx/.ashx/.php 等執行權限)。
  • 大檔/多檔:jQuery Form Plugin 支援多檔,大檔建議改用分片上傳(如 FineUploader、Plupload、或 HTML5 File API 手工分片)。

現代化替代方案

  • Dropzone.js / Uppy / FilePond:功能豐富、UI 現代、支援拖拽、進度條、分片、圖片預覽/裁切。
  • ASP.NET Core:使用 IFormFile 模型繫結,搭配前端元件上傳至 Controller/Minimal API。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved