using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Web;
|
using System.Web.Script.Serialization;
|
|
namespace CY.WebForm.Pages.business
|
{
|
/// <summary>
|
/// FileUploadHandler 的摘要说明
|
/// </summary>
|
public class FileUploadHandler : IHttpHandler
|
{
|
|
public void ProcessRequest(HttpContext context)
|
{
|
context.Response.ContentType = "application/json";
|
|
try
|
{
|
if (context.Request.Files.Count > 0)
|
{
|
HttpPostedFile file = context.Request.Files["file"];
|
|
// 验证文件
|
if (file.ContentLength > 0)
|
{
|
// 检查文件大小是否超过5MB
|
if (file.ContentLength > 5 * 1024 * 1024) // 5MB
|
{
|
throw new Exception("文件不能大于5M");
|
}
|
// 设置保存路径
|
string fileName = DateTime.Now.ToString("HHmmssfff")+ Path.GetFileName(file.FileName);
|
string riqi = DateTime.Now.ToString("yyyyMMdd");
|
string fileDirectory = "/UpFile/UpFile/" + riqi + "/";
|
if ((fileDirectory + fileName).Length>400) // 5MB
|
{
|
throw new Exception("文件名字过长");
|
}
|
string fileExtension = Path.GetExtension(fileName);
|
string savePath = context.Server.MapPath("~"+ fileDirectory) + fileName;
|
|
// 确保目录存在
|
if (!Directory.Exists(context.Server.MapPath("~"+ fileDirectory)))
|
{
|
Directory.CreateDirectory(context.Server.MapPath("~"+ fileDirectory));
|
}
|
|
// 保存文件
|
file.SaveAs(savePath);
|
|
// 返回JSON响应
|
var response = new
|
{
|
code = 1,
|
message = "文件上传成功",
|
fileName = fileName,
|
fileSize = file.ContentLength,
|
data = fileDirectory + fileName
|
};
|
|
context.Response.Write(new JavaScriptSerializer().Serialize(response));
|
}
|
else
|
{
|
throw new Exception("文件内容为空");
|
}
|
}
|
else
|
{
|
throw new Exception("没有接收到文件");
|
}
|
}
|
catch (Exception ex)
|
{
|
var errorResponse = new
|
{
|
code = 2,
|
message = ex.Message
|
};
|
|
context.Response.Write(new JavaScriptSerializer().Serialize(errorResponse));
|
}
|
}
|
|
public bool IsReusable
|
{
|
get
|
{
|
return false;
|
}
|
}
|
}
|
}
|