Files
thinkyu/教育訓練系統/Web/Services/TrainFareUploadHandler.ashx.cs
sryang 577060bc78 chore: 首次簽入 Thinkyu ASP.NET 專案
- 加入 Visual Studio / ASP.NET .gitignore
- 排除建置輸出、IDE 設定、NuGet packages、大型 MSI 安裝檔
2026-09-10 09:42:37 +08:00

75 lines
2.5 KiB
C#

using System;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using WebLib;
namespace Education.Services
{
public class TrainFareUploadHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json; charset=utf-8";
try
{
if (context.Request.Files.Count == 0)
{
WriteResponse(context, false, "沒有檔案被上傳", null);
return;
}
HttpPostedFile uploadFile = context.Request.Files[0];
if (uploadFile == null || uploadFile.ContentLength == 0)
{
WriteResponse(context, false, "檔案為空", null);
return;
}
string uploadDir = Path.Combine(context.Server.MapPath("~/"), "DocUpload");
if (!Directory.Exists(uploadDir))
{
Directory.CreateDirectory(uploadDir);
}
// 使用 TrainFareImport_時間戳.xlsx 格式命名
string timestamp = PublicVariable.TaiwanNow.ToString("yyyyMMdd_HHmmss_fff");
string tempFileName = Path.Combine(uploadDir, $"TrainFareImport_{timestamp}.xlsx");
// 確保檔案是 XLSX 或 XLS 格式
if (!uploadFile.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) &&
!uploadFile.FileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase))
{
WriteResponse(context, false, "只支援 .xlsx 或 .xls 格式的檔案", null);
return;
}
uploadFile.SaveAs(tempFileName);
context.Session["火車票價匯入檔案"] = tempFileName;
WriteResponse(context, true, "上傳成功", tempFileName);
}
catch (Exception ex)
{
WriteResponse(context, false, $"上傳失敗:{ex.Message}", null);
}
}
private void WriteResponse(HttpContext context, bool success, string message, string data)
{
var response = new
{
Success = success,
Message = message,
Data = data
};
context.Response.Write(JsonConvert.SerializeObject(response));
}
}
}