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

简介:

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

ASP.NET 使用js插件出现上传较大文件失败的解决方法(ajaxfileupload.js第一弹

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

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

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

下面给大家看一下界面:

1、初始情况下

wKioL1QPqAWjwLmCAAFKoBuNgKs619.jpg

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

wKiom1QPqA7g4NfwAAGbvTRIVAQ305.jpg

3、选择图片

wKioL1QPqDOSDOAOAANIt3_6m64414.jpg

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

wKioL1QPqFfA84n9AAH1a3wzRdI173.jpg

5、预览

wKioL1QPqGujorJ_AAH9eM8WkqY726.jpg

6、确定上传

wKioL1QPqH7wwSOpAAF4NCP95MA463.jpg

下面是部分代码

js部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
$.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" );
         }
         var  left_offset = ($(window).width() - 600) / 2; //显示在浏览器窗口比较正的位置,看着比较舒服
         var  top_offset = ($(window).height() - 278) / 3;
         var  theFloatDivHtml =  "<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=';' 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=';'>图片预览:" ;
         theFloatDivHtml +=  "<div class='img-portrait' style='padding-top:30px;'>" ;
         theFloatDivHtml +=  "<img src='' class='preview60' alt=''/>" ;
         theFloatDivHtml +=  "<span>60*60" ;
         theFloatDivHtml +=  "</div>" ;
         theFloatDivHtml +=  "<div style='float:left;'>" ;
         theFloatDivHtml +=  "<img src='' class='preview120' alt=''/>" ;
         theFloatDivHtml +=  "<span>120*120" ;
         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);
     });
     
     var  e = jQuery.Event( "click" );
 
     $( "body" ).delegate( "#btn_upload" "click" function  () {
 
     }).delegate( "#btn_upload" "change" function  () {
         var  curPATH = getFilePath($( this ).get(0));
         var  fileName = 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,需要先将图片上传到本地,这里也算是一个比较纠结的事情吧,因为如果想预览,除非用一些插件,否则使用的方法都得是先上传,再预览这样。这种来者都要不拒的事,看起来比较流氓哈~~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
         HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
         string  msg =  string .Empty;
         string  error =  string .Empty;
         string  imgurl =  string .Empty;
         protected  void  Page_Load( object  sender, EventArgs e)
         {
             if  (files.Count > 0)
             {
                  if  (System.IO.File.Exists(Server.MapPath( "/UploadImages/" ) + files[0].FileName))
                 {
                     msg =  "图片已存在" ;
                     error =  "1001" ;
                     string  res1 =  "{ error:'"  + error +  "', msg:'"  + msg +  "',imgurl:'"  + imgurl +  "'}" ;
                     Response.Write(res1);
                     Response.End(); return ;
                 }
                 if  (files[0].ContentLength > 4 * 1024 * 1024)
                 {
                     msg =  "图片大小不能超过4M" ;
                     error =  "1002" ;
                     string  res1 =  "{ 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;
                 string  res =  "{ error:'"  + error +  "', msg:'"  + msg +  "',imgurl:'"  + imgurl +  "'}" ;
                 Response.Write(res);
                 Response.End();
             }
         }

如何调用此插件

1
2
3
4
5
6
     <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://down.51cto.com/data/1871944


关于上传的Demo补充内容:

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

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

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

1
2
3
4
5
6
     <script type= "text/javascript" >
         $( function  () {
             $( "#btn_portrait" ).ShowTheFloatDiv($(img_portrait));
         })
         
     </script>

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










本文转自 我不会抽烟 51CTO博客,原文链接:http://blog.51cto.com/zhouhongyu1989/1550401,如需转载请自行联系原作者

目录
相关文章
|
16天前
|
JavaScript
鼠标事件(点击换色)分别使用js和jQuery代码实现
鼠标事件(点击换色)分别使用js和jQuery代码实现
26 1
|
3月前
|
设计模式 JavaScript 前端开发
必知的技术知识:jQuery插件开发精品教程,让你的jQuery提升一个台阶
必知的技术知识:jQuery插件开发精品教程,让你的jQuery提升一个台阶
32 1
|
5天前
|
编解码 JavaScript 前端开发
JS逆向浏览器脱环境专题:事件学习和编写、DOM和BOM结构、指纹验证排查、代理自吐环境通杀环境检测、脱环境框架、脱环境插件解决
JS逆向浏览器脱环境专题:事件学习和编写、DOM和BOM结构、指纹验证排查、代理自吐环境通杀环境检测、脱环境框架、脱环境插件解决
20 1
|
8天前
|
JavaScript
分别用jquery和js修改页面元素
分别用jquery和js修改页面元素
19 2
|
16天前
|
JavaScript Java
分别使用js与jquery写 单击按钮时出现内容 点击删除按钮不会再向下出现
分别使用js与jquery写 单击按钮时出现内容 点击删除按钮不会再向下出现
11 1
|
2天前
|
JavaScript 前端开发 测试技术
[译] 用 Vue.js 3 Composition API 创建 i18n 插件
[译] 用 Vue.js 3 Composition API 创建 i18n 插件
|
8天前
|
JavaScript 前端开发 数据安全/隐私保护
Validform jQuery插件详解
【8月更文挑战第21天】
|
2月前
|
JavaScript 前端开发 API
Chrome插件实现问题之 content_script.js能做什么
Chrome插件实现问题之 content_script.js能做什么
|
19天前
|
JavaScript 前端开发 容器
使用 jQuery 中的 this 实例
使用 jQuery 中的 this 实例
16 0
|
2月前
|
JavaScript
js好用的动态分页插件
js好用的动态分页插件是一款简单的分页样式插件,支持样式类型,当前页,每页显示数量,按钮数量,总条数,上一页文字,下一页文字,输入框跳转等功能。
27 1
下一篇
云函数