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

ASP.NET 整合 ajaxfileupload.js 實現非同步檔案上傳(含縮圖裁剪)

     編輯:ASP.NET 基礎

前言

ajaxfileupload.js 是一套輕量級 jQuery 外掛,封裝了隱藏 iframe 上傳細節,提供類似 AJAX 的介面,支援進度回呼、錯誤處理。本文分享專案實戰程式碼:前端驗證、上傳觸發、後端儲存與圖片裁剪縮圖完整流程。

前端完整程式碼

/* 修改頭像 - 上傳邏輯 */
function _sc() {
    $(".ckfile").html("").css("color", "#535353");
    $("#_userImgPath").val("");
    var str = $("#file").val();
    
    if ($.trim(str) == "") {
        $(".ckfile").html("請選擇檔案。").css("color", "red");
        return false;
    }
    
    // 檢查副檔名
    var postfix = str.substring(str.lastIndexOf(".") + 1).toUpperCase();
    if (postfix == "JPG" || postfix == "JPEG" || postfix == "PNG" || postfix == "GIF" || postfix == "BMP") {
        $('#showimg').attr('src', 'Images/loading.gif').attr("title", "上傳中,請稍後…");
        var path = "Upload/UserImg";
        
        $.ajaxFileUpload({
            url: '/Upload.aspx?path=Upload|UserImg&shape=100*100',
            secureuri: false,
            fileElementId: 'file',
            dataType: 'text',
            success: function (msg) {
                if (msg.lastIndexOf(path) == -1) {
                    // 後端回傳錯誤訊息
                    $(".ckfile").html(msg).css("color", "red");
                } else {
                    // 成功:顯示縮圖並存路徑
                    $('#showimg').attr('src', msg).attr("title", "我的頭像");
                    $("#_userImgPath").val(msg);
                }
            }
        });
    } else {
        $(".ckfile").html("檔案格式錯誤。").css("color", "red");
        return false;
    }
}

關鍵參數說明:

  • fileElementId:<input type="file"> 的 id,非 name。
  • dataType: 'text':後端直接 Response.Write 字串,非 JSON。
  • URL 參數 path、shape:傳遞儲存相對路徑與裁剪尺寸(寬*高)。

後端 Upload.aspx.cs 核心邏輯

public partial class Upload : BasePage
{
    private long size = 1024; // KB
    private string type = ".jpg|.jpeg|.png|.gif|.bmp";
    private string path = @"Upload/UserImg";
    private string shape = "100*100";

    protected void Page_Load(object sender, EventArgs e)
    {
        HttpFileCollection files = Request.Files;
        if (files != null && files.Count > 0)
        {
            // 以使用者 ID 命名,避免衝突
            name = BaseRole.Instance.UserId.ToString();
            
            // 覆寫 QueryString 參數
            if (Request.QueryString["size"] != null) size = Convert.ToInt32(Request.QueryString["size"]);
            if (Request.QueryString["path"] != null) path = Request.QueryString["path"].Replace('|', '/');
            if (Request.QueryString["name"] != null) name = Request.QueryString["name"];
            if (Request.QueryString["shape"] != null) shape = Request.QueryString["shape"];
            
            uploadMethod(files);
        }
    }

    public void uploadMethod(HttpFileCollection hc)
    {
        HttpPostedFile _file = hc[0];
        long _size = _file.ContentLength;
        
        // 基本驗證
        if (_size <= 0) { Response.Write("檔案錯誤。"); Response.End(); return; }
        if (size * 1024 < _size) { Response.Write("檔案過大,最大限制 " + size + "KB。"); Response.End(); return; }
        
        string _name = _file.FileName;
        string _ext = System.IO.Path.GetExtension(_name).ToLower();
        if (type.IndexOf(_ext) == -1) { Response.Write("檔案格式錯誤。"); Response.End(); return; }

        // 組合儲存路徑
        string _path = HttpContext.Current.Server.MapPath(path) + @"/" + name + _ext;
        
        try
        {
            int w = Convert.ToInt32(shape.Split('*')[0]);
            int h = Convert.ToInt32(shape.Split('*')[1]);
            // 呼叫自訂圖片處理元件:裁剪並壓縮品質 50
            ImageHelper.CutForCustom(_file, _path, w, h, 50);
            Response.Write(path + @"/" + name + _ext); // 回傳相對路徑供前端顯示
        }
        catch (Exception)
        {
            Response.Write("哎喲,出錯了。");
            Response.End();
        }
    }
}

ImageHelper.CutForCustom 簽名參考

public static void CutForCustom(HttpPostedFile postedFile, string savePath, int width, int height, int quality)
{
    using (var img = Image.FromStream(postedFile.InputStream))
    using (var thumb = new Bitmap(width, height))
    using (var g = Graphics.FromImage(thumb))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, 0, 0, width, height);
        
        var encoder = ImageCodecInfo.GetImageEncoders().First(c => c.MimeType == "image/jpeg");
        var params = new EncoderParameters(1);
        params.Param[0] = new EncoderParameter(Encoder.Quality, quality);
        thumb.Save(savePath, encoder, params);
    }
}

實務注意事項

  1. 檔名唯一性:範例使用 UserId 命名,若允許多張圖需加上 GUID 或時間戳。
  2. 目錄權限:Upload/UserImg 需給 IIS_IUSRS 寫入權限。
  3. 大檔案上傳:web.config 需設定 <httpRuntime maxRequestLength="..." /> 及 <security><requestFiltering><requestLimits maxAllowedContentLength="..." /></requestFiltering></security>(IIS 7+)。
  4. 安全性:僅驗證副檔名不足,建議讀取檔頭 Magic Number(如 JPEG: FF D8 FF)二次驗證,並將上傳目錄設為不可執行腳本。

總結

ajaxfileupload.js 讓舊專案以極低成本獲得「非同步上傳+即時預覽」體驗。搭配後端 ImageHelper 裁剪壓縮,可有效控制儲存體與頻寬。新專案建議直接使用 FormData + fetch/axios,架構更現代化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved