测试
HTML
选择文件:
ASHX
usingSystem;
usingSystem.Web;
usingSystem.IO;
usingSystem.Drawing;
usingSystem.Web.Script.Serialization;
publicclassUpload:IHttpHandler{
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/html";
if(context.Request.Files.Count>0)
{
HttpPostedFilefile1=context.Request.Files["myfile"];
helper.uploadImg(file1,"~/UploadFile/");//这里引用的是上面封装的方法
WriteJson(context.Response,"true","");
}
else
{
WriteJson(context.Response,"error","请选择要上传的文件");
}
}
publicboolIsReusable{
get{
returnfalse;
}
}
publicstaticvoidWriteJson(HttpResponseresponse,stringstatus1,stringmsg1,objectdata1=null)
{
response.ContentType="application/json";
varobj=new{status=status1,msg=msg1,data=data1};
stringjson=newJavaScriptSerializer().Serialize(obj);
response.Write(json);
}
}
publicclasshelper
{
///
///上传图片
///
///通过form表达提交的文件
///文件要保存的虚拟路径
publicstaticvoiduploadImg(HttpPostedFilefile,stringvirpath)
{
if(file.ContentLength>1024*1024*4)
{
thrownewException("文件不能大于4M");
}
stringimgtype=Path.GetExtension(file.FileName);
if(imgtype!=".jpg"&&imgtype!=".jpeg")//图片类型进行限制
{
thrownewException("请上传jpg或JPEG图片");
}
using(Imageimg=Bitmap.FromStream(file.InputStream))
{
stringsavepath=HttpContext.Current.Server.MapPath(virpath+file.FileName);
img.Save(savepath);
}
}
///
///上传文件
///
///通过form表达提交的文件
///文件要保存的虚拟路径
publicstaticvoiduploadFile(HttpPostedFilefile,stringvirpath)
{
if(file.ContentLength>1024*1024*6)
{
thrownewException("文件不能大于6M");
}
stringimgtype=Path.GetExtension(file.FileName);
//imgtype对上传的文件进行限制
if(imgtype!=".zip"&&imgtype!=".mp3")
{
thrownewException("只允许上传zip、rar....文件");
}
stringdirFullPath=HttpContext.Current.Server.MapPath(virpath);
if(!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹
{
Directory.CreateDirectory(dirFullPath);
}
file.SaveAs(dirFullPath+file.FileName);
}
} |