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。path、shape:傳遞儲存相對路徑與裁剪尺寸(寬*高)。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();
}
}
}
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);
}
}
Upload/UserImg 需給 IIS_IUSRS 寫入權限。web.config 需設定 <httpRuntime maxRequestLength="..." /> 及 <security><requestFiltering><requestLimits maxAllowedContentLength="..." /></requestFiltering></security>(IIS 7+)。ajaxfileupload.js 讓舊專案以極低成本獲得「非同步上傳+即時預覽」體驗。搭配後端 ImageHelper 裁剪壓縮,可有效控制儲存體與頻寬。新專案建議直接使用 FormData + fetch/axios,架構更現代化。