表单上传功能实现 ajax文件异步上传
项目中用户上传总是少不了的,下面就主要的列举一下表单上传和ajax上传!注意:context.Request.Files不适合对大文件进行操作,下面列举的主要对于小文件上传的处理!
资源下载:
一、jQuery官方下载地址:https://jquery.com/download/
一.表单上传:
html客户端部分:
选择文件:
一般处理程序服务器端:
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/plain";
HttpPostedFilefile1=context.Request.Files["file1"];
helper.uploadFile(file1,"~/upload/");//这里就是对相应方法进行调用
context.Response.Write("ok");//提示执行成功
}
上传代码的封装:
//////上传图片 /// ///通过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); }
二.Ajax文件异步上传:
注明:既然有了表单上传为什么又要ajax上传呢?因为表单上传过程中,整个页面就刷新了!ajax异步上传就可以达到只刷新局部位置,下面就简单看看ajax上传吧!
html客户端部分:
选择文件:
一般处理程序服务器端:
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/html";
if(context.Request.Files.Count>0)
{
HttpPostedFilefile1=context.Request.Files["myfile"];
helper.uploadFile(file1,"~/upload/");//这里引用的是上面封装的方法
WriteJson(context.Response,"true","");
}
else
{
WriteJson(context.Response,"error","请选择要上传的文件");
}
}
json代码封装:
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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。