jquery jaxfileupload File Upload plugin use detailed

Source: Internet
Author: User
Tags eval file size file upload json md5

Jaxfileupload Introduction

The Ajaxfileupload plug-in is a very simple jquery based asynchronous upload file plug-in, using the process found many with this name, based on the original version of the modified Plug-ins, the file version is more, I uploaded my own ajaxfileupload file to the blog park, the friends I want to use can download:/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 operations, to upload the attachment to the purpose of the main implementation in the source code have comments, it is not difficult to understand, we can also be based on this simple version to achieve more complex operations.

Ajaxfileupload Use instructions

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


$.ajaxfileupload ({
Type: "POST",//Request type: Post or get, be sure to set to post when you want to use data to submit a custom parameter
URL: "/shared/upload",//File Upload server-side request address
Secureuri:false,//whether to enable security commits, generally default to false on the line, no special treatment
Fileelementid: "Filepicture",//the ID of the file upload control <input type= "file" id= "Filepicture" name= "Filepicture" accept=. JP G,.jpeg,.png,.bmp "onchange=" Filepicturechange () "/>
DataType: "JSON",//return value type, generally set to JSON, and support html\xml\script type
Data: {"id": "1", "Name": "Test"},//For POST request submit custom parameters
Success:function (data, status) {//Server Success Response handler function
},
Error:function (data, status, E) {//server response failure handler function
}
});

First of all, add a reference to jquery and ajaxfileupload on the page, and here's the 2.1.4 version of jquery, which is largely unaffected by the test versions.

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

Page add input label with type file

<input type= "File" id= "Filepicture name=" Filepicture "accept=". Jpg,.jpeg,.png,.bmp "onchange=" FilePictureChange () "/>

By accept you can restrict the file types that can be selected by default when you open the File selection dialog box. The main definitions of file types are the following


*.3GPP audio/3gpp, VIDEO/3GPP 3GPP audio/video

*.AC3 AUDIO/AC3 AC3 Audio

*.asf allpication/vnd.ms-asf Advanced Streaming Format

*.au audio/basic au audio

*.css text/css cascading Style Sheets

*.csv Text/csv Comma separated Values

*.doc Application/msword MS Word Document

*.dot Application/msword MS Word Template

*.DTD application/xml-dtd Document Type Definition

*.DWG image/vnd.dwg AutoCAD Drawing Database

*.DXF image/vnd.dxf AutoCAD Drawing interchange Format

*.gif image/gif Graphic Interchange Format

*.htm text/html Hypertext Markup Language

*.html text/html Hypertext Markup Language

*.JP2 IMAGE/JP2 JPEG-2000

*.JPE image/jpeg JPEG

*.jpeg image/jpeg JPEG

*.jpg image/jpeg JPEG

*.js 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, Video/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 Format

*.png Image/png Portable Network Graphics

*.pot Application/vnd.ms-powerpoint MS PowerPoint Template

*.pps Application/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 Hypertext Markup Language

*.XLC Application/vnd.ms-excel MS Excel Chart

*.XLM Application/vnd.ms-excel MS Excel Macro

*.xls application/vnd.ms-excel MS Excel spreadsheet

*.xlt Application/vnd.ms-excel MS Excel Template

*.XLW Application/vnd.ms-excel MS Excel Workspace

*.xml Text/xml, application/xml extensible Markup Language

*.zip Aplication/zip Compressed Archive


I do not have a separate upload button, add the OnChange event, after the selection of files immediately upload files, onchange time is defined as follows.

function Filepicturechange () {
$.ajaxfileupload ({
URL: "/shared/upload",//server-side request address for file upload
Type: "Post",
Secureuri:false,//general set to False
Fileelementid: "Filepicture",//File upload Space id attribute
DataType: "JSON",//return value type is generally set to JSON
Success:function (data, status) {//Server Success Response handler function
alert (data.filename);
alert (Data.filepath);
alert (data.filesize);
},
Error:function (data, status, E) {//server response failure handler function
Alert (e);
}
});
};

The background controller processing method is as follows, uses the MD5 processing, the judgment file whether already exists, avoids the file duplicate uploads.


<summary>
Attachment upload
</summary>
<returns></returns>
Public ActionResult Upload ()
{
httpfilecollection files = System.Web.HttpContext.Current.Request.Files;
if (Files. Count = = 0) return Json ("Faild", jsonrequestbehavior.allowget);
MD5 md5hasher = new MD5CryptoServiceProvider ();
/* Computes the hash value for the specified Stream object.
byte[] Arrbythashvalue = Md5hasher.computehash (files[0). InputStream);
/* A string of hexadecimal pairs separated by hyphens, each of which represents the corresponding element in value; for example, "f-2c-4a" * *
String strhashdata = System.BitConverter.ToString (arrbythashvalue). Replace ("-", "");
String fileeextension = Path.getextension (Files[0]. FileName);
String uploaddate = DateTime.Now.ToString ("YyyyMMdd");
String virtualpath = String. Format ("/data/componentattachments/{0}/{1}{2}", Uploaddate, Strhashdata, fileeextension);
String fullfilename = Server.MapPath (virtualpath);
Create a folder, save a file
String path = Path.getdirectoryname (Fullfilename);
Directory.CreateDirectory (path);
if (! System.IO.File.Exists (Fullfilename))
{
Files[0]. SaveAs (Fullfilename);
}
String fileName = Files[0]. Filename.substring (Files[0]. Filename.lastindexof ("\") + 1, files[0]. Filename.length-files[0]. Filename.lastindexof ("\")-1);
String fileSize = GetFileSize (Files[0]. ContentLength);
Return Json (new {filename = filename, FilePath = virtualpath, FileSize = FileSize}, "text/html", Jsonrequestbehavior.all Owget);
}
<summary>
Get File size
</summary>
<param name= "bytes" ></param>
<returns></returns>
private string GetFileSize (long bytes)
{
Long kblength = 1024;
Long Mblength = 1024 * 1024;
if (bytes < kblength)
return bytes. 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 Some problems in the process of using ajaxfileupload

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 later version of the function, so it's time to copy the HandleError function to Ajaxfileupload.js.

Uploadhttpdata:function (r, type) {
var data =!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 ();

return data;
},
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]);
       }
   }

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.