jquery File Upload plugin ajaxfileupload used in ASP.

Source: Internet
Author: User
Tags jquery file upload

0 Ajaxfileupload Introduction

Ajaxfileupload plugin is a very simple jquery-based asynchronous upload file plug-in, using the process found many with the same name, based on the original version of the modified plug-in, the file version is more, I uploaded my own use of the Ajaxfileupload file to the blog park, want to use a friend can download: Http://files.cnblogs.com/files/fonour/ajaxfileupload.js.

The entire plug-in source code less than 200 lines, the implementation is very simple, the general principle is to create a hidden form by JS Dynamic, and then submit the operation, to achieve the purpose of uploading attachments, the main implementation in the source code has comments, not difficult to understand, we can also be based on this simple version to achieve more complex operations.

1 Ajaxfileupload Instructions for use

Ajaxfileupload is also very simple to use, call the Ajaxfileupload method, each configuration item is described in detail as follows:

$.ajaxfileupload ({type:"Post",//Request type: Post or get, must be set to post when you want to submit custom parameters using dataURL: "/shared/upload",//server-side request address for file uploadSecureuri:false,//whether to enable secure commit, the default is false on the line, no special handlingFileelementid: "Filepicture",//the file Upload control's ID <input type= "file" id= "Filepicture" name= "Filepicture" accept= ". Jpg,.jpeg,.png,.bmp" Onchange= " Filepicturechange () "/>DataType: "JSON",//return value type, generally set to JSON, also supports Html\xml\script typeData: {"id": "1", "Name": "Test"},//Submit custom parameters for post requestsSuccessfunction(data, status) {//Server Success Response handler function}, Error:function(data, status, E) {//Server Response Failure handler function            }        });

First, add a reference to jquery and ajaxfileupload on the page, and here's the 2.1.4 version of jquery, tested with each version basically has no effect.

<script src= ". /.. /content/js/jquery-2.1.4.min.js "></script><script src=". /.. /content/js/ajaxfileupload.js "></script>

Page to add an input label of type file

<type= "file"  ID= "Filepicture"  name= " Filepicture "  accept=". Jpg,.jpeg,.png,.bmp "  onchange=" Filepicturechange () "  />

By using accept, you can limit the file types that are selected by default when you open the File selection dialog box. The definition of a file type mainly includes the following

*.3GPP audio/3gpp, video/3gpp 3GPP audio/video*.ac3 audio/ac3 AC3 audio*.asf allpication/vnd.ms-asf Advanced Stre aming format*.au audio/basic au audio*.css text/css cascading Style sheets*.csv text/csv Comma separated Valu Es*.doc Application/msword MS Word Document*.dot application/msword MS Word template*.dtd APPLICATION/XML-DTD DOCU ment Type definition*.dwg image/vnd.dwg autocad Drawing database*.dxf image/vnd.dxf AutoCAD Drawing interchange Fo Rmat*.gif image/gif Graphic Interchange format*.htm text/html hypertext Markup language*.html text/html HyperTe XT Markup LANGUAGE*.JP2 image/jp2 jpeg-2000*.jpe image/jpeg jpeg*.jpeg image/jpeg jpeg*.jpg image/jpeg JPEG*.J S text/javascript, Application/javascript javascript*.json application/json javascript Object NOTATION*.MP2 Audio /mpeg, video/mpeg MPEG audio/video stream, layer Ii*.mp3 audio/mpeg MPEG Audio stream, layer Iii*.mp4 audio/mp4, vid Eo/mp4 MPEG-4 audio/vIdeo*.mpeg video/mpeg MPEG Video stream, layer ii*.mpg video/mpeg MPEG video stream, layer Ii*.mpp application/vnd. Ms-project MS Project Project*.ogg Application/ogg, Audio/ogg ogg vorbis*.pdf application/pdf portable Document Form At*.png image/png Portable Network graphics*.pot application/vnd.ms-powerpoint ms PowerPoint Template*.pps appli   Cation/vnd.ms-powerpoint MS PowerPoint slideshow*.ppt application/vnd.ms-powerpoint ms PowerPoint Presentation*.rtf  APPLICATION/RTF, text/rtf Rich text format*.svf image/vnd.svf simple Vector format*.tif image/tiff Tagged image    Format File*.tiff image/tiff Tagged image format File*.txt text/plain plain text*.wdb application/vnd.ms-works MS Works Database*.wps Application/vnd.ms-works works Text document*.xhtml application/xhtml+xml extensible HyperTe XT Markup LANGUAGE*.XLC Application/vnd.ms-excel MS Excel chart*.xlm application/vnd.ms-excel MS Excel MACRO*.XL S APPLICATION/VND.MS-EXcel MS Excel Spreadsheet*.xlt application/vnd.ms-excel MS Excel template*.xlw application/vnd.ms-excel MS Ex Cel Workspace*.xml text/xml, application/xml extensible Markup language*.zip Aplication/zip Compressed Archive

I do not have to put the upload button alone, add the onchange event, the file is uploaded immediately after the selection of files, onchange time is defined as follows.

functionFilepicturechange () {$.ajaxfileupload ({URL:"/shared/upload",//server-side request address for file uploadsType: "POST", Secureuri:false,//generally set to falseFileelementid: "Filepicture",//id attribute of file upload spaceDataType: "JSON",//The return value type is generally set to JSONSuccessfunction(data, status) {//Server Success Response handler functionalert (data.filename);                    alert (Data.filepath);                alert (data.filesize); }, Error:function(data, status, E) {//Server Response Failure handler functionalert (e);        }            }); };

Background controller processing method is as follows, using MD5 processing, determine whether the file exists, to avoid duplicate file upload.

/// <summary>        ///Attachment upload/// </summary>        /// <returns></returns>         PublicActionResult Upload () {httpfilecollection files=System.Web.HttpContext.Current.Request.Files; if(Files. Count = =0)returnJson ("Faild", Jsonrequestbehavior.allowget); MD5 Md5hasher=NewMD5CryptoServiceProvider (); /*computes the hash value of the specified Stream object*/            byte[] Arrbythashvalue = Md5hasher.computehash (files[0].            InputStream); /*A string of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value; for example, "f-2c-4a"*/            stringStrhashdata = System.BitConverter.ToString (arrbythashvalue). Replace ("-",""); stringFileeextension = Path.getextension (files[0].            FileName); stringUploaddate = DateTime.Now.ToString ("YYYYMMDD"); stringVirtualPath =string. Format ("/data/componentattachments/{0}/{1}{2}", Uploaddate, Strhashdata, fileeextension); stringFullfilename =Server.MapPath (virtualpath); //Create a folder, save a file              stringPath =Path.getdirectoryname (fullfilename);            Directory.CreateDirectory (path); if(!System.IO.File.Exists (Fullfilename)) {files[0].            SaveAs (Fullfilename); }            stringFileName = files[0]. Filename.substring (files[0]. Filename.lastindexof ("\\") +1, files[0]. filename.length-files[0]. Filename.lastindexof ("\\") -1); stringFileSize = GetFileSize (files[0].            ContentLength); returnJson (New{filename = filename, FilePath = virtualpath, FileSize = FileSize},"text/html", Jsonrequestbehavior.allowget); }        /// <summary>        ///Get File Size/// </summary>        /// <param name= "bytes" ></param>        /// <returns></returns>        Private stringGetFileSize (Longbytes) {            LongKblength =1024x768; LongMblength =1024x768*1024x768; if(Bytes <kblength)returnbytes. ToString () +"B"; if(Bytes <mblength)return decimal. Round (decimal. Divide (bytes, kblength),2). ToString () +"KB"; Else                return decimal. Round (decimal. Divide (bytes, mblength),2). ToString () +"MB"; }
2 Ajaxfileupload Some problems during use 2.0 Jquery.handleerror is not a function

Workaround:

The test handlererror only exists in the previous version of jquery-1.4.2, and there is no such function in later versions, so it is OK to copy the HandleError function into the ajaxfileupload.js.

Uploadhttpdata:function(r, type) {vardata =!type; Data= Type = = "xml" | | Data?R.responsexml:r.responsetext; //If The type is ' script ', eval it in global context        if(Type = = "Script") jquery.globaleval (data); //Get The JavaScript object, if JSON is used.        if(Type = = "JSON") eval ("Data =" +data); //eval ("data = \" "+ Data +" \ ");        //evaluate scripts within HTML        if(type = = "html") JQuery ("<div>"). HTML (data). Evalscripts (); returndata; }, HandleError:function(S, xhr, status, E) {//If A local callback is specified, fire it        if(s.error) {S.error.call (S.context||s, XHR, status, E); }        //Fire the Global callback        if(S.global) {(S.context? JQuery (S.context): jquery.event). Trigger ("Ajaxerror", [XHR, S, E]); }    }

jquery File Upload plugin ajaxfileupload used in ASP.

Related Article

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.