用iframe来实现文件的上传 伪Ajax
这里先给大家介绍下为什么叫伪Ajax方式上传,因为这个上传不会使当前页面产生刷新的效果,并且也没有用任何的Ajax技术,但是实现了页面无刷新的上传效果,因此小弟称为伪Ajax方式。
HtmlPage1.html页
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="jquery-1.7.1.js"></script> <script type="text/javascript"> $(function () { $('#fileUp').change(function () { $('#uploadLog').html('开始上传中....'); $('#formFile').submit(); }); }) function uploadSuccess(msg) { if (msg.split('|').length > 1) { $('#imgShow').attr('src', msg.split('|')[1]); $('#uploadLog').html(msg.split('|')[0]); } else { $('#uploadLog').html(msg); } } </script> </head> <body> <!-- 大家注意到这个form的target的了么?这个target属性的值frameFile,是form之后的iframe的name值, 这样的写法是让当前的form表单在提交表单内容的时候转交给iframe中进行页面中表单处理, 并且不会产生当前页面跳转! --> <form id='formFile' name='formFile' method="post" action='/uploads.aspx' target='frameFile' enctype="multipart/form-data"> <input type='file' id='fileUp' name='fileUp' /> <div id='uploadLog'></div> <br /> <img width='200' src='' height='200' id='imgShow' alt='缩略图' /> </form> <!-- 这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面, 但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的 页面文件上传,其实只是做一个一个小小的技巧! --> <iframe id='frameFile' name='frameFile' style='display: none;'></iframe> </body> </html>
Asp.Net Code: uploads页后台代码,前台没有代码
/// <summary> /// 页面加载.在这里我简单的写了下文件上传的处理Code /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { try { //获取当前Post过来的file集合对象,在这里我只获取了<input type='file' name='fileUp'/>的文件控件 HttpPostedFile file = Request.Files["fileUp"]; if (file != null) { //当前文件上传的目录 string path = Server.MapPath("~/Test/"); //当前待上传的服务端路径 string imageUrl = path + Path.GetFileName(file.FileName); //当前文件后缀名 string ext = Path.GetExtension(file.FileName).ToLower(); //验证文件类型是否正确 if (!ext.Equals(".gif") && !ext.Equals(".jpg") && !ext.Equals(".png") && !ext.Equals(".bmp")) { //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址 Response.Write("<script>window.parent.uploadSuccess('你上传的文件格式不正确!上传格式有(.gif、.jpg、.png、.bmp)');</script>"); Response.End(); } //验证文件的大小 if (file.ContentLength > 1048576) { //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址 Response.Write("<script>window.parent.uploadSuccess('你上传的文件不能大于1048576KB!请重新上传!');</script>"); Response.End(); } //开始上传 file.SaveAs(imageUrl); //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址 //如果成功返回的数据是需要返回两个字符串,我在这里使用了|分隔 例: 成功信息|/Test/hello.jpg Response.Write("<script>window.parent.uploadSuccess('Upload Success!|/Test/" + file.FileName + "');</script>"); Response.End(); } else { //上传失败 Response.Write("upload lose!"); Response.End(); } } catch { //上传失败 Response.Write("upload lose!"); Response.End(); } }

浙公网安备 33010602011771号