// 通用 AJAX 封裝
function ajaxPost(url, data, successCb) {
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: successCb,
error: (xhr, status, err) => console.error('AJAX Error:', status, err, xhr.responseText)
});
}
// 頁面邏輯
$(function() {
$('#fileUpload').on('change', function(e) {
const file = e.target.files[0];
if (!file) return;
if (!/^image\//.test(file.type)) return alert('請選擇圖片檔案');
if (file.size > 2 * 1024 * 1024) return alert('檔案不可超過 2MB');
const reader = new FileReader();
reader.onload = function(evt) {
// evt.target.result 為 Data URL (base64)
ajaxPost('PhotoHandler.aspx/SaveToSession', { imageData: evt.target.result }, function(res) {
if (res.d) {
$('#preview').attr('src', evt.target.result).show();
$('#hdnPhotoSaved').val('1');
alert('照片已暫存,請繼續填寫表單');
} else {
alert('暫存失敗:' + res.d);
}
});
};
reader.readAsDataURL(file);
});
$('#btnSubmit').on('click', function() {
if ($('#hdnPhotoSaved').val() !== '1') return alert('請先上傳照片');
// 正常提交表單,後端從 Session 取照片入庫
$('#mainForm').submit();
});
});
// PhotoHandler.aspx.cs
using System;
using System.Web;
using System.Web.Services;
public partial class PhotoHandler : System.Web.UI.Page
{
[WebMethod(EnableSession = true)]
public static string SaveToSession(string imageData)
{
try
{
// Data URL 格式: "data:image/png;base64,iVBORw0KGgo..."
if (string.IsNullOrEmpty(imageData) || !imageData.Contains("base64,"))
return "無效的圖片資料";
string base64 = imageData.Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
// 可選:驗證圖片格式、尺寸、壓縮
// using (var ms = new MemoryStream(bytes)) { var img = Image.FromStream(ms); ... }
HttpContext.Current.Session["UserPhoto"] = bytes;
return "OK";
}
catch (Exception ex)
{
// 記錄日誌
return "伺服器錯誤: " + ex.Message;
}
}
[WebMethod(EnableSession = true)]
public static byte[] GetPhotoFromSession()
{
return HttpContext.Current.Session["UserPhoto"] as byte[] ?? new byte[0];
}
}
// Confirm.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) LoadPhoto();
}
private void LoadPhoto()
{
byte[] photo = Session["UserPhoto"] as byte[];
if (photo != null && photo.Length > 0)
{
string base64 = Convert.ToBase64String(photo);
imgPreview.ImageUrl = "data:image/png;base64," + base64; // 或 ashx 處理器
btnSave.Enabled = true;
}
else
{
lblMsg.Text = "Session 中無照片,請重新上傳";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
byte[] photo = Session["UserPhoto"] as byte[];
if (photo != null)
{
// 存入資料庫 / 檔案系統
// new PhotoService().Save(userId, photo);
Session.Remove("UserPhoto"); // 用完清除
Response.Redirect("Success.aspx");
}
}
| 項目 | 說明 |
|---|---|
[WebMethod(EnableSession=true)] | 啟用 Session 存取,否則 HttpContext.Current.Session 為 null |
| Base64 傳輸 | JSON 安全、無需 multipart/form-data、易於除錯;體積約增大 33% |
| Session 存 byte[] | 直接存二進制避免重複編解碼;注意 Session 大小限制 (InProc 預設無上限,StateServer/SQL Server 需序列化) |
| 前端預覽 | Data URL 直接指派給 img.src 即時預覽,無需額外請求 |
| 錯誤處理 | 前後端統一 JSON 回應格式 {d: "OK"} / {d: "錯誤訊息"} |
Image.FromStream 驗證真實格式,防偽裝副檔名。ValidateAntiForgeryToken 或自訂 Token 驗證。HttpPostedFile 直接處理 multipart/form-data。此流程適用於「先上傳照片預覽,再送出主表單」的多步驟表單場景,利用 Session 做暫存橋樑,體驗流暢且實作簡潔。