jQuery插件之ajaxFileUpload(异步上传图片并实时显示,并解决onchange后ajaxFileUpload失效有关问题)
jQuery插件之ajaxFileUpload(异步上传图片并实时显示,并解决onchange后ajaxFileUpload失效问题)
参考学习:
第一篇:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
第二篇:http://www.jb51.net/article/50518.htm
第三篇:http://zhangzhaoaaa.iteye.com/blog/2200065
第四篇:http://blog.sina.com.cn/s/blog_6d3f840a0102vkpq.html (jQuery的ajaxFileUpload上传文件插件刷新一次才能再次调用触发change)
使用方法:
第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。
<script src="jquery-1.7.1.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
我的control代码如下:
1 public ActionResult EditPhoto(EmployeeModelUser u) 2 { 3 string realpath = ""; 4 string returnpath = ""; 5 string ID = ""; 6 string path=""; 7 if (Session["ID"] != null) 8 { 9 10 ID = this.HttpContext.Session["ID"].ToString(); 11 } 12 u.ID = Convert.ToInt32(ID); 13 14 if (u.Image != null && u.Image.ContentLength > 0) 15 { 16 string ext = u.Image.FileName; 17 u.PHOTONUMBER = ext; 18 path = "~/style/UserImages/" + ext; 19 realpath = Server.MapPath(path);//完整路径 20 u.Image.SaveAs(realpath); 21 returnpath = "/style/UserImages/" + ext;//返回view中img显示图片的路径 22 } 23 User user = new User(); 24 user.ID = u.ID; 25 user.PHOTONUMBER = u.PHOTONUMBER; 26 employeemanage.SaveImage(user); 27 28 return Content(returnpath);//文件存储路径 29 }
view代码如下:
<div class="new_portrait" id="Photo"> <div class="portrait_upload" id="portraitNo"> <span>上传自己的头像</span> </div> <div class="portraitShow dn" id="portraitShow"> <img width="120" height="120" id="PhotoNumber" src=""> <span>更换头像</span> </div> <input type="file" value="" title="支持jpg、jpeg、gif、png格式,文件小于5M" name="Image" onchange="ajaxFileUpload()" id="Image" class="myfiles"> <!-- <input type="hidden" id="headPicHidden" /> --> <span style="display: none;" id="headPic_error" class="error"></span> </div> <!--end .new_portrait-->
js代码
$("#Image").live("ajaxFileUpload", function () { //<input type="file" id="Image" name="Image" onchange="ajaxFileUpload()" /> $.ajaxFileUpload(); $("#Image").replaceWith($("#Image").clone(true)); $("#PhotoNumber").replaceWith('<img width="120" height="120" id="PhotoNumber" src="">'); }); function ajaxFileUpload() { //ajaxFileUpload上传用户头像(我的简历中的基本信息模块), <input type="file" id="Image" name="Image" onchange="ajaxFileUpload()" />成功 $.ajaxFileUpload ( { url: '/Employee/EditPhoto', //用于文件上传的服务器端请求地址 secureuri: false, //一般设置为false fileElementId: 'Image', //文件上传控间的id属性 <input type="file" id="Image" name="Image" /> dataType: 'HTML', //返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { //alert(data);成功 $("#PhotoNumber").attr("src",data); }, error: function (data, status, e)//服务器响应失败处理函数 { alert('上传图片失败'); } } ) return false; }
实现效果:
不足:第二遍ajaxFileUpload开始,能够上传(更新)图片,不过view中的<img/>图片显示不出来(就是view的<img>的src获取不到),待解决求指点