Home>

0Introduction to ajaxfileupload

The entire plugin source code is less than 200 lines, and the implementation is very simple.The general principle is to create hidden forms dynamically through js,And then submit.To achieve the purpose of uploading attachments,The main implementation has comments in the source code,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,Just call the ajaxfileupload method,The detailed description of each configuration item is as follows:

$.ajaxfileupload ({
   type:"post", //Request type:post or get, must be set to post when i want to submit custom parameters using data
   url:"/shared/upload", //Server-side request address for file upload
   secureuri:false, //Whether to enable secure commit,Generally defaults to false, no special treatment required
   fileelementid:"filepicture", //id of the file upload control<input type="file" name="filepicture" accept=". jpg, .jpeg, .png, .bmp" onchange="filepicturechange ()" /> ;
   datatype:"json", //Return value type,Generally set to json, also supports html \ xml \ script type
   data:{"id":"1", "name":"test"}, //used for submitting custom parameters for post requests
   success:function (data, status) {//The server successfully responds to the processing function
   },   error:function (data, status, e) {//Server response failure processing function
   }
  });

First add a reference to jquery and ajaxfileupload on the page. The 2.1.4 version used by jquery here has basically no effect on the various versions tested.

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

<script src="../../content/js/ajaxfileupload.js"></script>

Add an input tag of type file to the page

<input type="file" name="filepicture" accept=". Jpg, .jpeg, .png, .bmp" onchange="filepicturechange ()" />

Accept can limit the opening of the file selection dialog,File types that can be selected by default.The definitions of file types are 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 do n’t have a separate upload button here,Added onchange event to upload files immediately after selecting them,The onchange time is defined as follows.

function filepicturechange () {
   $.ajaxfileupload ({
    url:"/shared/upload", //Server-side request address for file upload
     type:"post",    secureuri:false, //Generally set to false
    fileelementid:"filepicture", //id attribute of file upload space
     datatype:"json", //The return value type is generally set to json
    success:function (data, status) {//The server successfully 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 processing method is as follows,Use md5 processing to determine whether the file already exists,Avoid duplicate file uploads.

///<summary>
  ///Updating files
  ///</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);
   /* A string of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value;
E.g. "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 document
    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>
  ///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 during the use of ajaxfileupload2.0 jquery.handleerror is not a function

Solution:

Tested handlererror only exists in versions before jquery-1.4.2,This function will not be available in future versions.So after copying the handleerror function into ajaxfileupload.js, that's it.

uploadhttpdata:function (r, type) {
  var data =! type;
  data=type == "xml" || data r 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]);
  }
 }
  • Previous Summary of using jQuery tree control zTree
  • Next Comparison of cookies and sessions based on java