You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
3.1 KiB
C#

2 months ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Collections;
using System.Web.Script.Serialization;
using System.Globalization;
namespace NetWorkHard.GlobalAshx
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class KindeditorUpload : IHttpHandler
{
//文件保存目录路径
private String savePath = "attached";
//定义允许上传的文件扩展名
private String fileTypes = "gif,jpg,jpeg,png,bmp,swf";
//最大文件大小
private int maxSize = 100000000;
public void ProcessRequest(HttpContext context)
{
HttpPostedFile imgFile = context.Request.Files["imgFile"];
if (imgFile == null)
{
showError(context, "请选择文件。");
}
string DirectoryName = context.Request.QueryString["DirectoryName"];
if (string.IsNullOrEmpty(DirectoryName) == true) DirectoryName = "attached";
savePath = System.AppDomain.CurrentDomain.BaseDirectory + DirectoryName;
if (Directory.Exists(savePath) == false) Directory.CreateDirectory(savePath);
String fileName = imgFile.FileName;
String fileExt = Path.GetExtension(fileName).ToLower();
ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));
if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
{
showError(context, "大小超过限制。");
}
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
{
showError(context, "上传文件扩展名是不允许的扩展名。");
}
String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
String filePath = savePath + "/" + newFileName;
imgFile.SaveAs(filePath);
String fileUrl = "../" + DirectoryName + "/" + newFileName;
Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = fileUrl;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
string jsonString = new JavaScriptSerializer().Serialize(hash);
context.Response.Write(jsonString);
context.Response.End();
}
private void showError(HttpContext context, string message)
{
Hashtable hash = new Hashtable();
hash["error"] = 1;
hash["message"] = message;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
string jsonString = new JavaScriptSerializer().Serialize(hash);
context.Response.Write(jsonString);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}