The JQuery File Upload plug-in ajaxFileUpload is used in Asp.net MVC,

Source: Internet
Author: User
Tags jquery file upload

The JQuery File Upload plug-in ajaxFileUpload is used in Asp.net MVC,
0 ajaxFileUpload Introduction

The ajaxFileUpload plug-in is a very simple Jquery-based Asynchronous File Upload plug-in. Many plug-ins with the same name and modified based on the original version are found during use, there are many file versions. I uploaded my own ajaxFileUpload file to the blog. If you want to use it, download: http://files.cnblogs.com/files/fonour/ajaxfileupload.js.

The source code of the entire plug-in is less than 200 lines. The implementation is very simple. The general principle is to dynamically create hidden forms through js, and then submit them to upload attachments, the main implementation is annotated in the source code, which is not difficult to understand. We can also implement more complex operations based on this simple version.

1 ajaxFileUpload instructions

The use of ajaxFileUpload is also very simple. You can call the ajaxFileUpload method. The configuration items are described as follows:

$. AjaxFileUpload ({type: "post", // request type: post or get. To use data to submit custom parameters, you must set it to post url: "/Shared/Upload", // secureuri: false, server-side request address for file Upload, // whether to enable secure submission. Generally, the default value is false. You do not need to handle fileElementId: "filePicture", // the id of the file upload Control <input type = "file" id = "filePicture" name = "filePicture" accept = ".jpg, .htm, .png, .bmp" onchange = "filePictureChange () "/> dataType:" json ", // return value type, which is generally set to json. The data: {" id ":" 1 ", "name": "test"}, // used to submit a post request. Custom parameter success: function (data, status) {// server success Response Processing function}, error: function (data, status, e) {// server response failed processing function }});

First, add a reference to JQuery and ajaxFileUpload on the page. Here, JQuery uses version 2.1.4, which has no effect on each version tested.

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

Add an input tag of file type on the page

<input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />

You can use accept to specify the file type that can be selected by default after the file selection dialog box is opened. The file types are defined as follows:

*.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 didn't put the upload button separately here. I added the onchange event and uploaded the file immediately after selecting the file. The onchange time is defined as follows.

Function filePictureChange () {$. ajaxFileUpload ({url: "/Shared/Upload", // server-side request address for file Upload type: "post", secureuri: false, // usually set to false fileElementId: "filePicture", // The id attribute dataType of the file upload space: "json", // the return value type is generally set to json success: function (data, status) {// the server responds to the processing function alert (data. fileName); alert (data. filePath); alert (data. fileSize) ;}, error: function (data, status, e) {// Server Response failure processing function alert (e );}});};

The background controller uses MD5 to determine whether a file already exists and avoid repeated file uploads.

/// <Summary> /// Upload attachments /// </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 ();/* calculate the hash value of the specified Stream object */byte [] arrbytHashValue = md5Hasher. computeHash (files [0]. inputStream);/* Stri consisting of hexadecimal pairs separated by hyphens Ng, where each pair represents the corresponding element in the 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 (virtual Path); // create a folder and save the 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. allowGet );} /// <summary> /// obtain the file size /// </summary> /// <param name = "bytes"> </param> /// <returns> </returns> private string GetFileSize (long bytes) {long kblength = 1024; long polling ength = 1024*1024; if (bytes <kblength) return bytes. toString () + "B"; if (bytes <symbol ength) return decimal. round (decimal. divide (bytes, kblength), 2 ). toString () + "KB"; else return decimal. round (decimal. divide (bytes, interval ength), 2 ). toString () + "MB ";}
2 problems in the use of ajaxFileUpload 2.0 jQuery. handleError is not a function

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 was 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]) ;}}

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.