ajax 上传
来源:互联网 发布:数据挖掘工具分类 编辑:程序博客网 时间:2024/05/02 02:57
<input type="file" name="file" id="photo" value="文件上传" >
//单传$(document).on('change','input[type="file"]',function() { ajaxFileUpload();})function ajaxFileUpload() { $.ajaxFileUpload ( { url: 'upload.php', //用于文件上传的服务器端请求地址 secureuri: false, //一般设置为false fileElementId: 'photo', //文件上传空间的id属性 <input type="file" id="file" name="file" /> dataType: 'json', //返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { var src="./img/"+data; //大图 $('#right').html('<img src="'+src+'" alt="" class="'+num+'" style="width: 600px;height: 500px">'); //缩略图 var pic=num; $("#"+num).children('img').eq(0).prop('src',src); }, error: function (data, status, e)//服务器响应失败处理函数 { alert(e); } } ) return false;}
ajaxfileupload.js
jQuery.extend({ 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] ); } }, createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; if(window.ActiveXObject) { if(typeof uri== 'boolean'){ iframeHtml += ' src="' + 'JavaScript:false' + '"'; } else if(typeof uri== 'string'){ iframeHtml += ' src="' + uri + '"'; } } iframeHtml += ' />'; jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0); }, createUploadForm: function(id, fileElementId, data) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data) { for(var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { jQuery(io).remove(); jQuery(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { var form = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId); if(form.encoding) { jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback ); return {abort: 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 ); // 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( xhr, status, e ); // If we have some XML response text (e.g. from an AJAX call) then log it in the console else if(xhr.responseText) console.log(xhr.responseText); }})
upload.php
<?php//包含一个文件上传类中的上传类include "fileupload.class.php";$up = new fileupload;//设置属性(上传的位置, 大小, 类型, 名是是否要随机生成)$up -> set("path", "./img/");$up -> set("maxsize", 2000000);$up -> set("allowtype", array("gif", "png", "jpg","jpeg"));$up -> set("israndname", true);//使用对象中的upload方法, 就可以上传文件, 方法需要传一个上传表单的名子 pic, 如果成功返回true, 失败返回falseif($up -> upload("file")) { //获取上传后文件名子 $arr= $up->getFileName(); echo json_encode($arr);} else { echo '<pre>'; //获取上传失败以后的错误提示 var_dump($up->getErrorMsg()); echo '</pre>';}
fileupload.class.php
<?php /** *file: fileupload.class.php 文件上传类FileUpload *本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传 */ class FileUpload { private $path = "./uploads"; //上传文件保存的路径 private $allowtype = array('jpg','gif','png'); //设置限制上传文件的类型 private $maxsize = 1000000; //限制文件上传大小(字节) private $israndname = true; //设置是否随机重命名文件, false不随机 private $originName; //源文件名 private $tmpFileName; //临时文件名 private $fileType; //文件类型(文件后缀) private $fileSize; //文件大小 private $newFileName; //新文件名 private $errorNum = 0; //错误号 private $errorMess=""; //错误报告消息 /** * 用于设置成员属性($path, $allowtype,$maxsize, $israndname) * 可以通过连贯操作一次设置多个属性值 *@param string $key 成员属性名(不区分大小写) *@param mixed $val 为成员属性设置的值 *@return object 返回自己对象$this,可以用于连贯操作 */ function set($key, $val){ $key = strtolower($key); if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){ $this->setOption($key, $val); } return $this; } /** * 调用该方法上传文件 * @param string $fileFile 上传文件的表单名称 * @return bool 如果上传成功返回数true */ function upload($fileField) { $return = true; /* 检查文件路径是滞合法 */ if( !$this->checkFilePath() ) { $this->errorMess = $this->getError(); return false; } /* 将文件上传的信息取出赋给变量 */ $name = $_FILES[$fileField]['name']; $tmp_name = $_FILES[$fileField]['tmp_name']; $size = $_FILES[$fileField]['size']; $error = $_FILES[$fileField]['error']; /* 如果是多个文件上传则$file["name"]会是一个数组 */ if(is_Array($name)){ $errors=array(); /*多个文件上传则循环处理 , 这个循环只有检查上传文件的作用,并没有真正上传 */ for($i = 0; $i < count($name); $i++){ /*设置文件信息 */ if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) { if(!$this->checkFileSize() || !$this->checkFileType()){ $errors[] = $this->getError(); $return=false; } }else{ $errors[] = $this->getError(); $return=false; } /* 如果有问题,则重新初使化属性 */ if(!$return) $this->setFiles(); } if($return){ /* 存放所有上传后文件名的变量数组 */ $fileNames = array(); /* 如果上传的多个文件都是合法的,则通过销魂循环向服务器上传文件 */ for($i = 0; $i < count($name); $i++){ if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) { $this->setNewFileName(); if(!$this->copyFile()){ $errors[] = $this->getError(); $return = false; } $fileNames[] = $this->newFileName; } } $this->newFileName = $fileNames; } $this->errorMess = $errors; return $return; /*上传单个文件处理方法*/ } else { /* 设置文件信息 */ if($this->setFiles($name,$tmp_name,$size,$error)) { /* 上传之前先检查一下大小和类型 */ if($this->checkFileSize() && $this->checkFileType()){ /* 为上传文件设置新文件名 */ $this->setNewFileName(); /* 上传文件 返回0为成功, 小于0都为错误 */ if($this->copyFile()){ return true; }else{ $return=false; } }else{ $return=false; } } else { $return=false; } //如果$return为false, 则出错,将错误信息保存在属性errorMess中 if(!$return) $this->errorMess=$this->getError(); return $return; } } /** * 获取上传后的文件名称 * @param void 没有参数 * @return string 上传后,新文件的名称, 如果是多文件上传返回数组 */ public function getFileName(){ return $this->newFileName; } /** * 上传失败后,调用该方法则返回,上传出错信息 * @param void 没有参数 * @return string 返回上传文件出错的信息报告,如果是多文件上传返回数组 */ public function getErrorMsg(){ return $this->errorMess; } /* 设置上传出错信息 */ private function getError() { $str = "上传文件<font color='red'>{$this->originName}</font>时出错 : "; switch ($this->errorNum) { case 4: $str .= "没有文件被上传"; break; case 3: $str .= "文件只有部分被上传"; break; case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break; case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break; case -1: $str .= "未允许类型"; break; case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break; case -3: $str .= "上传失败"; break; case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break; case -5: $str .= "必须指定上传文件的路径"; break; default: $str .= "未知错误"; } return $str.'<br>'; } /* 设置和$_FILES有关的内容 */ private function setFiles($name="", $tmp_name="", $size=0, $error=0) { $this->setOption('errorNum', $error); if($error) return false; $this->setOption('originName', $name); $this->setOption('tmpFileName',$tmp_name); $aryStr = explode(".", $name); $this->setOption('fileType', strtolower($aryStr[count($aryStr)-1])); $this->setOption('fileSize', $size); return true; } /* 为单个成员属性设置值 */ private function setOption($key, $val) { $this->$key = $val; } /* 设置上传后的文件名称 */ private function setNewFileName() { if ($this->israndname) { $this->setOption('newFileName', $this->proRandName()); } else{ $this->setOption('newFileName', $this->originName); } } /* 检查上传的文件是否是合法的类型 */ private function checkFileType() { if (in_array(strtolower($this->fileType), $this->allowtype)) { return true; }else { $this->setOption('errorNum', -1); return false; } } /* 检查上传的文件是否是允许的大小 */ private function checkFileSize() { if ($this->fileSize > $this->maxsize) { $this->setOption('errorNum', -2); return false; }else{ return true; } } /* 检查是否有存放上传文件的目录 */ private function checkFilePath() { if(empty($this->path)){ $this->setOption('errorNum', -5); return false; } if (!file_exists($this->path) || !is_writable($this->path)) { if (!@mkdir($this->path, 0755)) { $this->setOption('errorNum', -4); return false; } } return true; } /* 设置随机文件名 */ private function proRandName() { $fileName = date('YmdHis')."_".rand(100,999); return $fileName.'.'.$this->fileType; } /* 复制上传文件到指定的位置 */ private function copyFile() { if(!$this->errorNum) { $path = rtrim($this->path, '/').'/'; $path .= $this->newFileName; if (@move_uploaded_file($this->tmpFileName, $path)) { return true; }else{ $this->setOption('errorNum', -3); return false; } } else { return false; } } }
0 0
- ajax上传
- ajax上传
- ajax 上传
- ajax 上传
- Ajax上传文件 (JQuery Ajax&原生Ajax)
- ajax上传文件
- 模仿AJAX上传文件
- ajax文件上传
- ajax文件上传应用
- ajax 文件上传进度条
- jQuery AJAX 文件上传
- C#+ajax上传文件
- LINUX + AJAX上传数据
- Ajax附件上传
- ajax上传文件
- ajaxfileupload ajax文件上传
- 浅析Ajax文件上传
- 非ajax上传
- C++ 模板详解(一)
- java
- NYOJ 977 最大的最小公倍数
- Spring Security3.0升级至3.2.4版本注意事项
- 厉害了我的CSDN
- ajax 上传
- 15种排序方法 未完结
- QQ空间后台架构优化之路
- Eclipse菜单栏 source Refactor详解
- 操作系统实践之第二章(分页机制)
- KVC/KVO原理详解及编程指南
- PreparedStatement与Statement对比、sql语句的被注入问题
- LeetCode笔记:160. Intersection of Two Linked Lists
- 动态规划 矩阵连乘问题