jQuery自制上传头像插件-附带Demo实例(ajaxfileupload.js第三弹)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

这篇文章主要是对前两篇关于Ajaxfileupload.js插件的文章

《asp.net使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹)》

《jQuery 关于ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二弹)》

的一个收关。但是最初也是因为想做这么一个功能,一点一点的引发出了好多问题,不断去学习,研究,才写了这三篇。

早些时候已经实现了上传头像的功能,但是代码却是零零散散的,有html,有jQuery还有c#,所以就决定把这个功能独立出来,当个插件用会方便很多。而事实是在封装成插件的过程中,也学到了很多知识。

下面给大家看一下界面:

1、初始情况下

2、点击上传头像,弹出选择,预览浮动框

3、选择图片

4、确定后,符合要求,会提示成功,不符合要求,也会做出相应的提示

5、预览

6、确定上传

下面是部分代码

js部分:

$.fn.extend({

ShowTheFloatDiv:function(obj) {

$(this).click(function() {

$("body").find("*").not("div.float-outer").attr("disabled","disabled");var$float= jQuery.CreateTheFloatDiv();

$img_outer_obj = obj;

});

}

});

$.extend({

CreateTheFloatDiv:function() {if($(".float-outer").size() == 1) {return$(".float-outer");

}varleft_offset = ($(window).width() - 600) / 2;//显示在浏览器窗口比较正的位置,看着比较舒服vartop_offset = ($(window).height() - 278) / 3;vartheFloatDivHtml ="<div class='float-outer' style='left:"+ left_offset +"px;top:"+ top_offset +"px;'>";

theFloatDivHtml +="<div class='float-header float-border'>上传头像</div>";

theFloatDivHtml +="<div class='float-content'>";

theFloatDivHtml +="<div class='content-first-row'>文件名:";

theFloatDivHtml +="<input type='text' id='tb_filename' style='width:350px;' readonly /> ";

theFloatDivHtml +="<input type='button' id='btn_selectfile' value='选择图片' style='margin-left:-10px;' />";

theFloatDivHtml +="<input type='file' id='btn_upload' name='btn_upload' style='display:none;' accept='.jpg,.bmp,.gif' />";

theFloatDivHtml +="</div>";

theFloatDivHtml +="<div class='content-second-row'>";

theFloatDivHtml +="<span class='img-portrait' style='width:80px;'>图片预览:</span>";

theFloatDivHtml +="<div class='img-portrait' style='padding-top:30px;'>";

theFloatDivHtml +="<img src='' class='PReview60' alt=''/>";

theFloatDivHtml +="<span>60*60</span>";

theFloatDivHtml +="</div>";

theFloatDivHtml +="<div style='float:left;'>";

theFloatDivHtml +="<img src='' class='preview120' alt=''/>";

theFloatDivHtml +="<span>120*120</span>";

theFloatDivHtml +="</div>";

theFloatDivHtml +="</div>";

theFloatDivHtml +="</div>";

theFloatDivHtml +="<div class='float-footer float-border'>";

theFloatDivHtml +="<input type='submit' value='确定' id='btn_ok' />";

theFloatDivHtml +="<input type='button' value='取消' id='btn_cancel' />";

theFloatDivHtml +="</div>";

theFloatDivHtml +="</div>";

$("body").append(theFloatDivHtml);return$(".float-outer");

}

});var$img_outer_obj;

$(function() {//取消事件$("body").delegate("#btn_cancel","click",function() {

$(".float-outer").remove();

$("body").find("*").removeAttr("disabled");

});//选择图片事件$("body").delegate("#btn_selectfile","click",function() {

$("#btn_upload").trigger(e);

});vare = jQuery.Event("click");

$("body").delegate("#btn_upload","click",function() {

}).delegate("#btn_upload","change",function() {varcurPATH = getFilePath($(this).get(0));varfileName = curPATH.substring(curPATH.lastIndexOf("\\") + 1);

var type = curPATH.substring(curPATH.lastIndexOf('.') + 1).toLowerCase();

if (type == "jpg" || type == "gif" || type == "bmp") {

$("input#tb_filename").val(fileName);

if ($("input#tb_filename").val() == "") {

alert("请先上传文件!");

return;

}

$.ajaxFileUpload

(

{

url: '/UploadPortrait.aspx', //用于文件上传的服务器端请求地址,需要根据实际情况进行修改

secureuri: false, //一般设置为false

fileElementId: $("input#btn_upload").attr("id"), //文件上传空间的id属性 <input type="file" id="file" name="file" /> //$("form").serialize(),表单序列化。指吧所有元素的ID,NAME 等全部发过去

dataType: 'json', //返回值类型 一般设置为json

complete: function () {//只要完成即执行,最后执行

},

success: function (data, status) //服务器成功响应处理函数

{

if (typeof (data.error) != 'undefined') {

if (data.error != '') {

if (data.error == "1001") {

}

else if (data.error == "1002") {

$("input#tb_filename").val("");

$(".preview60").attr("src", "");

$(".preview120").attr("src", "");

}

alert(data.msg);

return;

} else {

alert(data.msg);

}

}

$(".preview60").attr("src", data.imgurl);

$(".preview120").attr("src", data.imgurl);

},

error: function (data, status, e)//服务器响应失败处理函数

{

alert(e);

}

}

)

return false;

}

else {

alert("请选择正确的图片格式(.jpg|.gif|.bmp)");

}

});

$("body").delegate("#btn_ok", "click", function () {

$img_outer_obj.attr("src", $(".preview120").attr("src"));

$(".float-outer").remove();

$("body").find("*").removeAttr("disabled");

});

//移动浮动框

var offset_left, offset_top, moveFlag;

$("body").delegate(".float-header", "mousedown", function (e) {

moveFlag = true;

offset_left = e.pageX - $(this).offset().left;

offset_top = e.pageY - $(this).offset().top;

$("body").delegate(".float-header", "mousemove", function (e) {

if (moveFlag) {

$(".float-outer").CSS("left", e.pageX - offset_left + "px").css("top", e.pageY - offset_top + "px");

}

}).delegate(".float-header", "mouseup",function() {

moveFlag =false;

})

})

});

C#部分:

因为上传文件用到了ajax,需要先将图片上传到本地,这里也算是一个比较纠结的事情吧,因为如果想预览,除非用一些插件,否则使用的方法都得是先上传,再预览这样。这种来者都要不拒的事,看起来比较流氓哈~~

HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;stringmsg =string.Empty;stringerror =string.Empty;stringimgurl =string.Empty;protectedvoidPage_Load(objectsender, EventArgs e)

{if(files.Count > 0)

{if(System.IO.File.Exists(Server.MapPath("/UploadImages/") + files[0].FileName))

{

msg ="图片已存在";

error ="1001";stringres1 ="{ error:'"+ error +"', msg:'"+ msg +"',imgurl:'"+ imgurl +"'}";

Response.Write(res1);

Response.End();return;

}if(files[0].ContentLength > 4 * 1024 * 1024)

{

msg ="图片大小不能超过4M";

error ="1002";stringres1 ="{ error:'"+ error +"', msg:'"+ msg +"',imgurl:'"+ imgurl +"'}";

Response.Write(res1);

Response.End();return;

}try{

files[0].SaveAs(Server.MapPath("/UploadImages/") + System.IO.Path.GetFileName(files[0].FileName));

}catch(System.IO.DirectoryNotFoundException)

{

}

msg =" 上传成功! 图片大小为:"+ files[0].ContentLength +"K";

imgurl ="/UploadImages/"+ files[0].FileName;stringres ="{ error:'"+ error +"', msg:'"+ msg +"',imgurl:'"+ imgurl +"'}";

Response.Write(res);

Response.End();

}

}

如何调用此插件

<script type="text/javascript">

$(function() {

$("#btn_portrait").ShowTheFloatDiv($("#img_portrait"));

})

</script>

注意事项

必须在“上传头像”按钮所在页面引入以下几个文件

UploadPortrait.css

ajaxfileupload.js

jquery-2.0.3.min.js(jQuery插件要求在1.4.2版本之上)

UploadPortrait.js

如果大家在使用过程中出现问题,可以先把前面相关的两篇文章略读一下,大概就能找到原因了。

大致这个功能就是如上这样,感兴趣的朋友可以从下面的地址下载Demo运行看看。此外想说的是,因为是头像嘛,一定要存数据库的,但是在Demo里我并没有写,这个东西就是看大家想怎么实现了,要是我的话,因为之前预览都要将图片存到本地,所以如果存数据库的话,当然是会存图片的url了,那这样就比较好办了。

总的来说,要比想像中的快些完成了这个插件,功能倒是达到了自己的预期,但是界面来说,还有很长的一段路要走。第一次写jQuery插件,很多东西都不太专业,希望大牛们能多多给予指正和帮助。

Demo下载地址:http://files.cnblogs.com/zhouhongyu1989/uploadportrait%E4%B8%8A%E4%BC%A0%E5%A4%B4%E5%83%8FDemo.rar

关于上传的Demo补充内容:

上传的demo有两个问题需要说明一下,希望下载的朋友能够注意到,并流畅运行。

1、因为demo是ASP.NET项目,所以大家如想正常运行,需要在本地新建一个web项目,把我上传的uploadportrait.csproj这个文件添加进去。下次我会直接打包一个完整的web项目再上传,这次没做好希望大家给予谅解。另,我开发的时候Visual Studio版本为2010,这个望大家注意一下。

2、在调用插件的代码部分,demo里写的是

<script type="text/Javascript">

$(function () {

$("#btn_portrait").ShowTheFloatDiv($("#img_portrait"));

})

</script>

应该把$(img_portrait)改成$("#img_portrait"),这个也是自己的失误,下回会注意。

补充:

《jQuery 关于IE9上传文件无法进入后台问题的原因及解决办法(ajaxfileupload.js第四弹)》

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航