asp.net mvc using the jquery plugin ajaxfileupload upload file _ practical Tips

Source: Internet
Author: User
Tags eval md5 save file zip

0 Ajaxfileupload Profile

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, and the friends I want to use can download: Http://xiazai.jb51.net/201611/yuanma/ajaxfileupload (jb51.net). rar.

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.

1 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 as Post URL when you want to use data to submit a custom parameter
   : "/shared/upload",     //File Upload server-side request address
   secureuri:false,//      whether to enable security submission, the general default is false on the line, without special handling
   Fileelementid: "Filepicture",   //File Upload control 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 type
   data: {" id ":" 1 " , "name": "Test"},//For POST request submit custom parameter
   success:function (data, status) {  //server successful response handler
   },
   error: function (data, status, E) {//server response failed handler
   }
  });

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

Copy Code code as follows:
<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 type for file uploads
     : "POST" ,
    Secureuri:false,//general set to False
    Fileelementid: "Filepicture",//File upload Space id attribute
     dataType: "JSON",//return value type General settings for JSON
    success:function (data, status) {//Server Success Response processing function
      alert (data.filename);
     alert (data.filepath);
     alert (data.filesize);
    },
    error:function (data, status, E) {//server response failure handling 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 of the specified Stream object/byte[] Arrbythashvalue = Md5hasher.computehash (files[0).
   InputStream); /* A string of hexadecimal pairs separated by hyphens in which each pair represents the corresponding element in value, such as "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 folder, save 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>///<retur
   Ns></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]);
  }
 

For more highlights, please click on the "jquery Upload operation Summary" for in-depth study and research.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.