JQuery Homemade upload Avatar Plugin-demo instance (ajaxfileupload.js third bullet)

Source: Internet
Author: User

This article is mainly about the first two articles about the Ajaxfileupload.js plugin

The solution to the failure of uploading large files using the Ajaxfileupload.js plugin (ajaxfileupload.js first bomb)

"JQuery on Ajaxfileupload.js plug-in analysis (ajaxfileupload.js second bomb)"

A collection of customs. But originally also because want to do such a function, 1.1 point of cause a lot of problems, continue to study, study, just wrote these three.

Earlier has realized the ability to upload avatars, but the code is fragmented, there is HTML, there is jquery and C #, so decided to separate this function, when a plug-in will be more convenient. The fact is that in the encapsulation into the process of plug-ins, but also learned a lot of knowledge.

Let's look at the interface below:

1, the initial situation

2, click Upload Avatar, pop-up selection, preview the floating box

3. Select Picture

4, after the confirmation, meet the requirements, will prompt success, do not meet the requirements, will also make corresponding tips

5. Preview

6. Confirm Upload

Here's some code

JS section:

$.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;//Display in the browser window compare positive position, look more comfortable        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 ' > Upload avatar </div>"; Thefloatdivhtml + ="<div class= ' float-content ' >"; Thefloatdivhtml + ="<div class= ' content-first-row ' > FileName:"; Thefloatdivhtml + ="<input type= ' text ' id= ' tb_filename ' style= ' width:350px; ' readonly/> '; Thefloatdivhtml + ="<input type= ' button ' id= ' btn_selectfile ' value= ' select Picture ' 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; ' > Picture preview:</span> "; Thefloatdivhtml + ="<div class= ' img-portrait ' style= ' padding-top:30px; ' > "; Thefloatdivhtml + =" '; Thefloatdivhtml + ="<span>60*60</span>"; Thefloatdivhtml + ="</div>"; Thefloatdivhtml + ="<div style= ' float:left; ' > "; Thefloatdivhtml + =" '; Thefloatdivhtml + ="<span>120*120</span>"; Thefloatdivhtml + ="</div>"; Thefloatdivhtml + ="</div>"; Thefloatdivhtml + ="</div>"; Thefloatdivhtml + ="<div class= ' float-footer float-border ' >"; Thefloatdivhtml + ="<input type= ' submit ' value= ' OK ' id= ' btn_ok '/> '; Thefloatdivhtml + ="<input type= ' button ' value= ' Cancel ' id= ' btn_cancel '/> '; Thefloatdivhtml + ="</div>"; Thefloatdivhtml + ="</div>"; $("Body"). append (thefloatdivhtml);return$(". Float-outer"); }});var$img _outer_obj;$ (function() {//Cancel event$("Body").Delegate("#btn_cancel","click",function() {        $(". Float-outer"). Remove (); $("Body"). Find ("*"). Removeattr ("Disabled"); });//Select Picture Event$("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 ("Please upload the file first!");            Return } $.ajaxfileupload ({url: '/uploadportrait.aspx ',//server-side for file upload, please The address needs to be modified according to the actual situation secureuri:false,//general set to False Fileelementid: $ ("Input#btn_upload"). attr ("Id"),//File upload Space id attribute <input type="File"Id="File"Name="File"/>//$ ("Form"). Serialize (), form serialization. All the elements of the id,name, etc. dataType: ' json ',//return value type is generally set to JSON complete:function () {//Only                        To complete execution, last execution}, success:function (data, status)//server Success Response Handler {                                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)//server response failure Handler {alert (e);        }}) return false; } else {alert ("Please select the correct picture format (. jpg|. Gif|. Bmp");    }    }); $("Body"). Delegate ("#btn_ok", "Click", function () {$img _outer_obj.attr ("Src", $(". preview120"). attr ("Src")); $(".float-outer"). Remove (); $("Body"). Find ("*"). Removeattr ("Disabled");    });    Mobile Floating box 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 # section:

Because the upload file to use Ajax, you need to upload the image to the local, here is a more tangled matter, because if you want to preview, unless you use some plug-ins, otherwise the method must be uploaded first, and then preview this. This kind of thing is not rejected, looks like a rogue ha ~ ~

httpfilecollection files = System.Web.HttpContext.Current.Request.Files;stringmsg =string. Empty;stringError =string. Empty;stringImgurl =string. Empty;protected voidPage_Load (Objectsender, EventArgs e) {if(Files. Count > 0) {if(System.IO.File.Exists (Server.MapPath ("/uploadimages/") + files[0]. FileName) {msg ="Picture already exists"; Error ="1001";stringRes1 ="{error: '"+ Error +"', msg: '"+ msg +"', Imgurl: '"+ Imgurl +"'}";                    Response.Write (RES1); Response.End ();return; }if(Files[0]. ContentLength > 4 * 1024x768 * 1024x768) {msg ="image size cannot exceed 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 ="Upload success!" The image size is: "+ files[0]. ContentLength +"K"; Imgurl ="/uploadimages/"+ files[0]. FileName;stringres ="{error: '"+ Error +"', msg: '"+ msg +"', Imgurl: '"+ Imgurl +"'}";                Response.Write (RES);            Response.End (); }        }

How to call this plugin

    <script type="Text/javascript">        $ (function () {            $ ("#btn_portrait"). Showthefloatdiv ($ ("#img_portrait"));        })            </script>

Precautions

The following files must be introduced on the page where the upload Avatar button is located

Uploadportrait.css

Ajaxfileupload.js

Jquery-2.0.3.min.js (jquery plugin requires above 1.4.2 version)

Uploadportrait.js

If you have problems in the use of the process, you can first of the two related articles skim a bit, probably can find the reason.

Roughly this function is as above, interested friends can download demo run to see from the address below. Also want to say is, because is the avatar, must save the database, but in the demo I did not write, this thing is to see how you want to realize, if I say, because before the preview to the picture to the local, so if the database, of course, will save the image of the URL, then this is better to do.

In general, faster than expected to complete the plug-in, the function is to achieve their own expectations, but the interface, there is a long way to go. The first time to write jquery plugin, a lot of things are not too professional, I hope that Daniel can give a lot of correction and help.

Demo: Http://files.cnblogs.com/zhouhongyu1989/uploadportrait%E4%B8%8A%E4%BC%A0%E5%A4%B4%E5%83%8FDemo.rar

JQuery Homemade upload Avatar Plugin-demo instance (ajaxfileupload.js third bullet)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.