ajax+php上传文件源码,可正常运行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a906904948/article/details/83651919

完整的jquery Ajax+php上传文件源码,可直接放到网站目录下运行

index.html

 <html>
	<head>
		<title>TEST</title>
		<meta charset="UTF-8">
		<link href="https://cdn.bootcss.com/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
	</head>
	<body>
		<input type="file" id="test1">
		<input type="text" class="test2">
		<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
		<script src="https://cdn.bootcss.com/toastr.js/latest/toastr.min.js"></script>
		<script src="jquery-uploader.js"></script>
		<script>
		$(function(){
				$("#test1").uploader({
					ele:'.test2',		
					clear:true		
				});
		})	
		</script>
	</body>
</html>

jquery-uploader.js

(function($){
    /*
    *  $(ele).uploader({
           ele:'',		//接收返回值的Dom
           formate:[],	//上传格式 array
           path:'',	//接口
           clear:true, //上传成功后是否清除Input值  dafault true;
       })
    *
    */

    $.fn.uploader=function(options){
        if(typeof options!=='undefined' && typeof options !=='object'){ throw new Error('config error');}
        var _Default_responseEle=this;
        var _Default_formate=['jpg','jpeg','png','gif'];
        var _Default_path='./upload/?m=fileupload';
        var _Default_clear=true;
        var _resonseEle=typeof options==='undefined' || typeof options.ele =='undefined' ? _Default_responseEle : options.ele;
        var _formate=typeof options ==='undefined' || typeof options.formate=='undefined' || typeof options.formate!=='object' ? _Default_formate :options.formate;
        var _path=typeof options==='undefined' || typeof options.path=='undefined' || options.path=='' ? _Default_path : options.path;
        var _clear=typeof options==='undefined' || typeof options.clear=='undefined' || options.clear=='' ? _Default_clear : options.clear;
        var ajaxUploader={
            config:{
                formate:_formate,
                path:_path
            },
            formate:function(ele){
                var uploader=this,
                    tmp=$(ele).val(),
                    name=tmp.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi, "$1"),
                    suffix = tmp.replace(/.+\./, "").toLocaleLowerCase();
                return uploader.config.formate.indexOf(suffix)<0?false:true;
            },
            init:function(ele,valele){
                var uploader=this;
                $(ele).change("propertychange", function() {
                    var formData = new FormData();
                    formData.append('file', $(this)[0].files[0]);
                    uploader.formate(ele)?
                        $.ajax({
                            url:uploader.config.path,
                            type:'post',
                            cache: false,
                            processData: false,
                            contentType: false,
                            data:formData,
                            beforeSend:function(){
                                uploader.before();
                            }}).then(function(res){
                            uploader.response(res,ele,valele);
                        },function(){
                            uploader.error();
                        })
                        :uploader.warning();
                });
            },
            response:function(obj,e,valele){
                var o=typeof obj !=='object' ? JSON.parse(obj) :obj,uploader=this;
                return o.errcode=='0'? uploader.success(e,o.imgpath,valele) : uploader.error(o.errortype);
            },
            before:function(){
                return toastr.info("文件上传中,请稍后");
            },
            success:function(e,v,ele){
                return toastr.success("文件上传成功") && $(ele).val(v) && this.empty(e);
            },
            error:function(t){
                return toastr.error("上传失败"+typeof t =='undefined' ? '':'原因'+t);
            },
            empty:function(e){
                _clear? $(e).val(''): '';
            },
            warning:function(){
                var msg=function(){
                    var t='';
                    for(var i in _formate){
                        t+=_formate[i]+','
                    }
                    return t.substring(0,t.length-1);
                }
                toastr.warning('上传文件格式有误,只支持'+msg()+'格式')
            }
        };
        ajaxUploader.init(this,_resonseEle);
    }
})(jQuery);

upload/index.php [linux要给upload目录写入权限]

<?php
/*
 * @ 上传文件API接口
 * @ URL 
 * @ tips:
		文件上传接口配置信息
			单个图片		  maxSize 1MB	
			允许上传文件类型  jpg png gif
 * @return
		errcode 
			0 上传成功
				fiename		//原文件名
				filepath	//存储相对路径
				imgpath		//URL路径		
				config		//配置信息
					maxsize		//允许最大值
					allowtype	//允许格式
					filepath	//上传目录
			1 格式不允许
			2 大小超出限制
			3 服务器配置出错
			4 没有被上传
 * 	
 */ 


header("Content-type: text/html; charset=utf-8"); 
date_default_timezone_set('PRC');

$m=isset($_GET['m'])==''?'null':$_GET['m'];
if($m=='fileupload'){
	function makedir($file){
		$dirname=date("Ymd");
		$dir = iconv("UTF-8", "GBK", "$file/$dirname");
		if (!file_exists($dir)){
			mkdir ($dir,0777,true);
		}
		return $dir;
	}
	if ( !empty( $_FILES ) ) {
		
		/*
		 * 上传文件配置
		 */
	    
	    //文件大小 单位 MB
		$maxsize=10;   
		//限制上传文件类型 jpg png gif
		$allowtype=array('image/jpeg','image/jpg','image/png','image/gif','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		//文件上传目录   .表示当前目录
		$uploadPath=".";
		//创建子目录
		$filePath=makedir($uploadPath);
		//上传文件重命名
		$fileName = date('YmdHis').rand(10,99);   	
		//返回接口配置信息
		$arr_conf=array(
			'maxsize' =>$maxsize.'MB',
			'allowtype' =>json_encode($allowtype),
			'filepath' =>$filePath
		);
		
		$bit=$maxsize * 1024 * 1024;
		$array = explode('.',$_FILES['file']['name']);
		$filetype= $array[1];
		if(! in_array(($_FILES['file']['type']),$allowtype)){
			$arr=array(
				'errcode'  =>'1',
				'errortype' =>'不允许的文件类型',
				'config' =>$arr_conf
			);
			echo json_encode($arr);exit;
		}
		if($_FILES['file']['size']>=$bit){
			$arr=array(
				'errcode'  =>'2',
				'errortype' =>'超出文件限定大小',
				'config' =>$arr_conf
			);
			echo json_encode($arr);exit;
		}
		
		$tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
		if(move_uploaded_file($tempPath,$filePath.'/'.$fileName.'.'.$filetype)){
		    $tmp=$filePath.'/'.$fileName.'.'.$filetype;
		    $tmp_=str_replace('./', '', $tmp);
			$arr=array(
				'errcode' =>'0',
				'msg'  =>'文件上传成功',
				'fiename' =>$_FILES['file']['name'],
				'filepath' =>$filePath.'/'.$fileName.'.'.$filetype,
			    'xlspath' =>__DIR__.'/'.$tmp_,
				'imgpath' => 'http://'.$_SERVER['HTTP_HOST'].str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME'])).substr($filePath,1).'/'.$fileName.'.'.$filetype,
			    'realpath' => str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME'])).substr($filePath,1).'/'.$fileName.'.'.$filetype,
			    
			    'config' =>$arr_conf
			);
			echo json_encode($arr);exit;
		}else{
			$arr=array(
				'errcode' =>'3',
				'errortype' =>'文件移动失败,请检查文件权限',
				'config' =>$arr_conf
			);
			echo json_encode($arr);exit;
		}
		
		
	} else {
		$arr=array(
				'errcode'  =>'4',
				'errortype' =>'没有文件被上传',
				'config' =>$arr_conf
		);
		echo json_encode($arr);exit;
	}
}
?>

页面截图
下载地址:csdn下载
哪里有不足的地方希望多多指正

猜你喜欢

转载自blog.csdn.net/a906904948/article/details/83651919