JS File Upload plugin (support upload progress information) __js

Source: Internet
Author: User

1. The source code is as follows

/** * @author Sun Qillao Description: Version 1.0/function Xuploader () {/** * Corresponding input Object * * var fileInput;

	/** * Global callback function, external incoming * * var onuploading, onsuccess, onfailed, oncanceled;
	
	/** * FormData object, storage will upload the file with the accompanying information, with information in the form of key value to deposit/var formData = new FormData ();

	/** * Core Upload class * * var xhr = new XMLHttpRequest (); /** * Initialization File Upload object emId for input [type = file] ID * * * this.bindfiles = function (emId) {fileInput = document.getelementbyi
		D (EMID);
			Fileinput.onchange = function () {var files = fileinput.files;
			var fileInfo = {};
				if (files) {var fileSize = 0;
				for (var i in files) {fileSize + = files[i].size;
					} if (FileSize > 1024 * 1024 * 1024) {fileSize = (math.round (fileSize * 100/(1024 * 1024 * 1024))/100)
				. toString () + ' G ';  else if (fileSize > 1024 * 1024 && fileSize < 1024 * 1024 * 1024) {fileSize = (Math.Round (fileSize *
				(1024 * 1024)). ToString () + ' M '; else if (fIlesize > 1024 && fileSize < 1024 * 1024) {fileSize = (Math.Round (fileSize * 100/1024)/100)
				. toString () + ' K ';
				else {fileSize = (Math.Round (fileSize)). ToString () + ' B ';
	}} else {}};
		/** * Upload file/this.upload = function (URL) {var name = Fileinput.getattribute (' name ');
		var filelists = fileinput.files;
			if (filelists) {for (var i in filelists) {formdata.append (name, filelists[i]);
		} Xhr.upload.addEventListener ("Progress", this.onprogress, false);
		Xhr.addeventlistener ("Load", This.oncomplete, false);
		Xhr.addeventlistener ("Error", this.onfailed, false);
		Xhr.addeventlistener ("Abort", this.oncanceled, false);
	Xhr.open ("POST", url);//modify into its own interface xhr.send (FormData);
	/** * Cancel upload/This.cancel = function () {xhr.abort (); /** * File crosses */this.onprogress = function (evt) {if (evt.lengthcomputable) {var percentcomplete = Math.ceil ( evt.loaded * 100/EVT. Total) + '% ';
			var resp = {loader:evt.loaded, total:evt.total, percent:percentcomplete};
			if (onuploading) {onuploading (RESP);
			} else {if (onuploading) {onuploading (' unable to compute '); 
		}}/** * File uploaded * * * this.oncomplete = function (evt) {if (onsuccess) {onsuccess (evt.target.responseText);
	} console.log ("onsuccess");
		/** * File upload failed/this.onfailed = function (evt) {if (onfailed) {onfailed ("failed");
	} console.log ("onfailed");
		/** * File Cancel upload/this.oncanceled = function (evt) {if (oncanceled) {oncanceled ("canceled");
	} console.log ("oncanceled");  /** * Set upload with the key value of the information */this.setparams = function (mapData) {if (MapData && mapData instanceof)
			{var keyarray = Mapdata.keyset ();
				for (var i = 0; i < mapdata.size (); i++) {var k = keyarray[i];
			Formdata.append (K,mapdata.get (k));
		} else {alert ("parameter data type error, must be HashMap object");
	}
	}
	/** * Set up upload process callback monitor/This.setonuploadinglistener = function (callback) {onuploading = callback;
	/** * Set upload successful callback monitor/This.setonsuccesslistener = function (callback) {onsuccess = callback;
	/** * Set upload failed callback monitor/This.setonfailedlistener = function (callback) {onfailed = callback;
	/** * Settings Cancel upload callback monitor/This.setoncanceledlistener = function (callback) {oncanceled = callback;
	}/** * Defines key value pairs/function HashMap () {//define length var = 0;

	Create an object, var obj = new Object ();
	/** * To determine whether the map is empty/this.isempty = function () {return length = 0;

	};
	/** * Determines whether the object contains a given key/This.containskey = function (key) {return (key in obj);

	};
				/** * Determines whether the object contains the given value */This.containsvalue = function (value) {for (var key in obj) {if (obj[key] = = value) {
			return true;
	return false;

	};
		/** * Add data to map */this.put = function (key, value) {if (!this.containskey (key)) {length++;
	} Obj[key] = value;

	}; /**
	 * Obtains value/This.get = function (key) {return This.containskey (key) Obj[key] According to the given key: null;

	}; /** * Delete a value according to the given key * * This.remove = function (key) {if (This.containskey (key) && (delete obj[key)) {Le
		ngth--;

	}
	};
		/** * Gets all value/this.values = function () {var _values = new Array () in the map;
		for (var key in obj) {_values.push (Obj[key]);
	return _values;

	};
		/** * Obtains all key/This.keyset = function () {var _keys = new Array () in map;
		for (var key in obj) {_keys.push (key);
	return _keys;

	};
	/** * Gets the length of map * * * this.size = function () {return length;

	};
		/** * Empty map */this.clear = function () {length = 0;
	obj = new Object ();

	};
		/** * Converts hashmap to JSON/this.tostring = function () {var s = "[";
		var Keyarray = This.keyset ();
			for (var i = 0; i < length; i++, S + = ', ') {var k = keyarray[i];
		S + + "{'" + K + "':" + obj[k] + "}";
		} s = s.substring (0, s.length-1); if (S!= "") {s+= "]";
	return s; }
}


2. How to use

1. Introduction of Xuploader.js

2. Define the input control on the page

<input type= "file" name= "Files" id= "Fileuploader" multiple/>  
<input type= "button" onclick= "UploadFile ()" value= "Upload"/>

3.js Code

Upload Progress callback functions function
    Getuploadinginfo (resp) {
        console.log (resp);
    }
    Create file Upload object
    var uploader = new Xuploader ();
    Initializes
    the Uploader.bindfiles ("Fileuploader") with the input box ID;
    Set upload Progress callback function
    Uploader.setonuploadinglistener (getuploadinginfo);
   Upload
  function UploadFile () {  
      //except file with key value pairs with information
      var params = new HashMap ();
      Params.put ("Test", "123");
      Params.put ("Test2", "1232");
      Set Upload parameters
      uploader.setparams (params);
      Upload the file with the attached parameter information, parameters for their own interface
      uploader.upload (' Uploadcommonsoftware ');
      }  
3. Operating Results


















GitHub plugin Address

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.