使用 jQuery Form Plugin 配合 Generic Handler (.ashx) 實現無刷新(AJAX)檔案上傳,上傳完成即時回顯縮圖。相容 IE、Firefox、Chrome 等主流瀏覽器。
jquery.min.jsjquery.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。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;
}
context.Server.MapPath 將虛擬路徑轉實體路徑儲存,回傳虛擬路徑供前端 img.src 使用。Guid.NewGuid() + 原始副檔名,或依上傳者 ID + 時間戳命名。UserFiles/temp 需給 IIS AppPool 身分寫入權限,但不可執行腳本(IIS 設定 Handler Mapping 移除 .aspx/.ashx/.php 等執行權限)。IFormFile 模型繫結,搭配前端元件上傳至 Controller/Minimal API。