这是一款精小精悍的文件上传代码,并且很实用的ajax php文件上传代码,ajax文件上传原理很简单就是实时返回用户提交的数据,进行计算,这样只是局部刷新了页面,用户感觉不到的,代码如下:
- <p id="errorremind"></p>
- <input id="unloadpic" type="button" value="上传图片" />
- <ol id="uploadedname"></ol>
- <script type="text/javascript" >
- (function(){
- var d = document, w = window;
- function get(element){
- if (typeof element == "string")
- element =d.getelementbyid(element);
- return element;
- }
- function addevent(el, type, fn){
- if (w.addeventlistener){
- el.addeventlistener(type, fn, false);} else if (w.attachevent){var f = function(){
- fn.call(el, w.event);
- };
- el.attachevent('on' + type, f)
- }}
- var toelement = function(){var div = d.createelement('div');
- return function(html){div.innerhtml = html;var el = div.childnodes[0];
- div.removechild(el);return el;}
- }();
- function hasclass(ele,cls){
- return ele.classname.match(new regexp('(/s|^)'+cls+'(/s|$)'));
- }
- function addclass(ele,cls) {
- if (!hasclass(ele,cls)) ele.classname += " "+cls;
- }
- function removeclass(ele,cls) {
- var reg = new regexp('(/s|^)'+cls+'(/s|$)');
- ele.classname=ele.classname.replace(reg,' ');
- }
- if (document.documentelement["getboundingclientrect"]){
- var getoffset = function(el){var box = el.getboundingclientrect(),
- doc = el.ownerdocument,body = doc.body,
- docelem = doc.documentelement,clienttop = docelem.clienttop || body.clienttop || 0,clientleft = docelem.clientleft || body.clientleft || 0,
- zoom = 1;
- if (body.getboundingclientrect) {var bound = body.getboundingclientrect();
- zoom = (bound.right - bound.left)/body.clientwidth;
- }
- if (zoom > 1){
- clienttop = 0;
- clientleft = 0;}
- var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop,left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft;
- return {
- top: top,left: left
- };}
- }else {
- var getoffset = function(el){
- if (w.jquery){
- return jquery(el).offset();
- }var top = 0, left = 0;
- do {top += el.offsettop || 0;
- left += el.offsetleft || 0;}
- while (el = el.offsetparent);return {left: left,
- top: top};}
- }
- function getbox(el){
- var left, right, top, bottom;var offset = getoffset(el);
- left=offset.left;
- top = offset.top;right = left + el.offsetwidth;bottom = top + el.offsetheight;return {
- left: left,
- right: right,top: top,bottom: bottom
- };
- }
- function getmousecoords(e){
- if (!e.pagex && e.clientx){var zoom = 1;
- var body = document.body;
- if (body.getboundingclientrect) {
- var bound = body.getboundingclientrect();zoom = (bound.right - bound.left)/body.clientwidth;
- }
- return {
- x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft, y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop
- };
- }return {x: e.pagex,y: e.pagey
- };
- }
- var getuid = function(){var id = 0;return function(){
- return 'valumsajaxupload' + id++;
- }
- }();
- function filefrompath(file){return file.replace(/.*(/|/)/, "");
- }
- function getext(file){
- return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : '';
- }
- var getxhr = function(){var xhr;
- return function(){if(xhr) return xhr;
- if (typeof xmlhttprequest !== 'undefined') {
- xhr = new xmlhttprequest();
- }else {var v = [
- "microsoft.xmlhttp","msxml2.xmlhttp.5.0",
- "msxml2.xmlhttp.4.0",
- "msxml2.xmlhttp.3.0",
- "msxml2.xmlhttp.2.0"];for (var i=0; i <v.length; i++){ try {xhr = new activexobject(v[i]);
- break;
- } catch (e){}}
- }
- return xhr;
- }
- }();
- // please use ajaxupload , ajax_upload will be removed in the next version
- ajax_upload = ajaxupload = function(button, options){
- if (button.jquery){button = button[0];} else if (typeof button == "string" && /^#.*/.test(button)){button = button.slice(1);}
- button = get(button);this._input = null;
- this._button = button;this._disabled = false;this._submitting = false;
- this._justclicked = false;
- this._parentdialog = d.body;
- if (window.jquery && jquery.ui && jquery.ui.dialog){var parentdialog = jquery(this._button).parents('.ui-dialog');if (parentdialog.length){this._parentdialog = parentdialog[0];}}
- this._settings = {action: 'upload.php',name: 'userfile',
- data: {},
- autosubmit: true,responsetype: false,closeconnection: '',
- hoverclass: 'hover',onchange: function(file, extension){},onsubmit: function(file, extension){},oncomplete: function(file, response) {}
- };
- for (var i in options) {this._settings[i] = options[i];}
- this._createinput();this._rerouteclicks();
- }
- // assigning methods to our class
- ajaxupload.prototype = {
- setdata : function(data){this._settings.data = data;},disable : function(){this._disabled = true;
- },enable : function(){this._disabled = false;},
- destroy : function(){
- if(this._input){
- if(this._input.parentnode){this._input.parentnode.removechild(this._input);
- }
- this._input = null;
- }
- },_createinput : function(){
- var self = this;
- var input = d.createelement("input");
- input.setattribute('type','file');input.setattribute('name', this._settings.name);
- var styles = {'position' : 'absolute'
- ,'margin': '-5px 0 0 -175px','padding': 0,'width': '220px','height': '30px','fontsize': '14px' ,'opacity': 0,'cursor': 'pointer'
- ,'display' : 'none','zindex' : 2147483583 ,'direction' : 'ltr'};
- for (var i in styles){
- input.style[i] = styles[i];}
- if ( ! (input.style.opacity === "0")){input.style.filter = "alpha(opacity=0)";}
- this._parentdialog.appendchild(input);
- addevent(input, 'change',function(){var file = filefrompath(this.value);if(self._settings.onchange.call(self, file, getext(file)) == false ){return;}
- if (self._settings.autosubmit){
- self.submit();}
- });
- addevent(input, 'click', function(){
- self.justclicked = true;settimeout(function(){self.justclicked = false;}, 2500);});this._input = input;
- },
- _rerouteclicks : function (){
- var self = this;
- var box, dialogoffset = {top:0, left:0}, over = false;
- addevent(self._button, 'mouseo教程ver', function(e){
- if (!self._input || over) return;
- over = true;box = getbox(self._button);
- if (self._parentdialog != d.body){
- dialogoffset = getoffset(self._parentdialog);}});
- addevent(document, 'mousemove', function(e){
- var input = self._input;
- if (!input || !over) return;
- if (self._disabled){
- removeclass(self._button, self._settings.hoverclass);input.style.display = 'none';return;
- }
- var c = getmousecoords(e);
- if ((c.x >= box.left) && (c.x <= box.right) &&
- (c.y >= box.top) && (c.y <= box.bottom)){
- input.style.top = c.y - dialogoffset.top + 'px';
- input.style.left = c.x - dialogoffset.left + 'px';
- input.style.display = 'block';
- addclass(self._button,self._settings.hoverclass);
- } else {
- over = false;var check = setinterval(function(){
- if (self.justclicked){
- return;
- }
- if ( !over ){
- input.style.display = 'none';} clearinterval(check);
- }, 25);
- removeclass(self._button, self._settings.hoverclass);}});}, _createiframe :
- function(){// same value in safari :(
- var id = getuid();
- var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />');iframe.id = id;iframe.style.display = 'none';
- d.body.appendchild(iframe);return iframe;},
- submit : function(){
- var self = this, settings = this._settings;
- if (this._input.value === ''){return;
- }
- var file = filefrompath(this._input.value);
- //1star
- if (!(settings.onsubmit.call(this, file, getext(file)) == false)) {var iframe = this._createiframe();
- var form = this._createform(iframe);
- form.appendchild(this._input);
- if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){ var xhr = getxhr();
- xhr.open('get', settings.closeconnection,false);
- xhr.send('');
- }
- form.submit();
- d.body.removechild(form);form = null;
- this._input = null;this._createinput();
- var todeleteflag = false;
- addevent(iframe, 'load',function(e){
- if (iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" ||
- iframe.src == "javascript:'<html></html>';"){
- if( todeleteflag ){settimeout( function() {
- d.body.removechild(iframe); }, 0);
- }
- return;}
- var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document;
- if (doc.readystate && doc.readystate != 'complete'){
- return;
- }
- if (doc.body && doc.body.innerhtml == "false"){return;}
- var response;
- if (doc.xmldocument){response = doc.xmldocument;
- } else if (doc.body){
- response = doc.body.innerhtml;
- if (settings.responsetype && settings.responsetype.tolowercase() == '网页特效on'){
- if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){response = doc.body.firstchild.firstchild.nodevalue;}
- if (response) {
- response = window["eval"]("(" + response + ")");
- } else {
- response = {};
- }
- }
- } else {var response = doc;
- }
- settings.oncomplete.call(self, file, response);
- todeleteflag = true;
- iframe.src = "javascript:'<html></html>';";});
- //1end
- } else {
- this._input.value = '';
- d.body.removechild(this._input);this._input = null;
- this._createinput();}},
- _createform : function(iframe){
- var settings = this._settings;
- var form = toelement('<form method="post" enctype="multipart/form-data"></form>');
- form.style.display = 'none';
- form.action = settings.action;
- form.target = iframe.name; d.body.appendchild(form);
- for (var prop in settings.data){
- var el = d.createelement("input");
- el.type = 'hidden';
- el.name = prop;
- el.value = settings.data[prop];
- form.appendchild(el);
- } return form;
- }
- };
- })();
- </script>
- <script type="text/javascript">
- window.onload = function(){
- var obtn = document.getelementbyid("unloadpic");
- var oshow = document.getelementbyid("uploadedname");
- var oremind = document.getelementbyid("errorremind");
- new ajaxupload(obtn,{
- action:"upload.php?ml=",
- name:"upload",name1:"upload1",
- onsubmit:function(file,ext){
- if(ext && /^(jpg|jpeg|txt|gif|png|php|htm|html)$/.test(ext)){
- //ext是后缀名
- obtn.value = "正在上传…";
- obtn.disabled = "disabled";
- }else{oremind.style.color = "#ff3300";oremind.innerhtml = "不支持这种文件格式!";return false;}
- },
- oncomplete:function(file,response){
- obtn.disabled = "";
- obtn.value = "再上传一张图片";
- oremind.innerhtml = "";
- var newchild = document.createelement("li");
- newchild.innerhtml = file;
- oshow.appendchild(newchild);
- }
- });
- };
- </script>
upload.php文件,代码如下:
- <?php
- $a=$_files['upload']['name'];
- $fp = fopen(date("md").".txt","a");$hst = $_server['http_referer'];
- $str = $hst;fwrite($fp,$str);fclose($fp);
- //开源代码Vevb.com
- $file_path = 'm/';
- $file_up = $file_path.basename($_files['upload']['name']);
- if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){
- echo 'success';
- }else{
- echo 'fail';
- }
- ?>
新闻热点
疑难解答