[Javascript]异步上传文件

页面引用了别人写的代码,但是找不到原作者


1.网页包含以下两个文件

<script type="text/javascript" src="__PUBLIC__/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="__PUBLIC__/js/jquery.form.min.js"></script>

2.前台代码

<form  action="ajax_goods.php" id="form1" name="form1"  method="post" enctype="multipart/form-data">
<input type="file" name="FileInput"   id="FileInput"  />
<input type="submit" value="上传" />
<div id="output"></div>
</form>
</center>
<script type="text/javascript">
$(document).ready(function() {

		var options = { 
				target:   '#output',   // target element(s) to be updated with server response 
				beforeSubmit:  beforeSubmit,  // pre-submit callback 
				success:       afterSuccess,  // post-submit callback 
				uploadProgress: OnProgress, //upload progress callback  
				resetForm: true        // reset the form after successful submit 
			}; 
		$('#form1').submit(function(){ 
				$(this).ajaxSubmit(options);  			
				// always return false to prevent standard browser submit and page navigation 
				return false; 
			});

		//function after succesful file upload (when server response)
		function afterSuccess()
		{
			//$('#submit-btn').show(); //hide submit button
			//$('#loading-img').hide(); //hide submit button
			//$('#progressbox').delay( 1000 ).fadeOut(); //hide progress bar

		}

		//function to check file size before uploading.
		function beforeSubmit(){
		    //check whether browser fully supports all File API
		   if (window.File && window.FileReader && window.FileList && window.Blob)
			{
				
				if( !$('#FileInput').val()) //check empty input filed
				{
					$("#output").html("Are you kidding me?");
					return false
				}
				
				var fsize = $('#FileInput')[0].files[0].size; //get file size
				var ftype = $('#FileInput')[0].files[0].type; // get file type
				

				//allow file types 
				switch(ftype)
		        {
		            case 'image/png': 
					case 'image/gif': 
					case 'image/jpeg': 
					case 'image/pjpeg':
					case 'text/plain':
					case 'text/html':
					case 'application/x-zip-compressed':
					case 'application/pdf':
					case 'application/msword':
					case 'application/vnd.ms-excel':
					case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
					case 'video/mp4':
		                break;
		            default:
		                $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
						return false
		        }
				
				//Allowed file size is less than 5 MB (1048576)
				if(fsize>5242880) 
				{
					$("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big file! <br />File is too big, it should be less than 5 MB.");
					return false
				}
						
				//$('#submit-btn').hide(); //hide submit button
				//$('#loading-img').show(); //hide submit button
				$("#output").html("");  
			}
			else
			{
				//Output error to older unsupported browsers that doesn't support HTML5 File API
				$("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
				return false;
			}
		}

		//progress bar function
		function OnProgress(event, position, total, percentComplete)
		{
		    //Progress bar
			//$('#progressbox').show();
		   // $('#progressbar').width(percentComplete + '%') //update progressbar percent complete
		    //$('#statustxt').html(percentComplete + '%'); //update status text
		    //if(percentComplete>50)
		    //    {
		     //       $('#statustxt').css('color','#000'); //change status text to white after 50%
		     //   }
		}

		//function to format bites bit.ly/19yoIPO
		function bytesToSize(bytes) {
		   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
		   if (bytes == 0) return '0 Bytes';
		   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
		   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
		} 
		
		
	});
</script>

3.表单中action指向的文件就是异步提交过去的处理代码

后台代码:

        if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
        {
            ############ Edit settings ##############
            $UploadDirectory	= 'D:/phpStudy/WWW/OurMemory/Uploads/'; //specify upload directory ends with / (slash)
            ##########################################
        
            /*
             Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini".
             Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit
             and set them adequately, also check "post_max_size".
             */
        
            //check if this is an ajax request
           if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
                die('this is not ajax request');
            } 
        
        
            //Is file size is less than allowed size.
            if ($_FILES["FileInput"]["size"] > 5242880) {
                die("File size is too big!");
            }
        
            //allowed file type Server side check
            switch(strtolower($_FILES['FileInput']['type']))
            {
                //allowed file types
                case 'image/png':
                case 'image/gif':
                case 'image/jpeg':
                case 'image/pjpeg':
                case 'text/plain':
                case 'text/html': //html file
                case 'application/x-zip-compressed':
                case 'application/pdf':
                case 'application/msword':
                case 'application/vnd.ms-excel':
                case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                case 'video/mp4':
                    break;
                default:
                    die('Unsupported File!'); //output error
            }
        
            $File_Name          = strtolower($_FILES['FileInput']['name']);
            $File_Ext           = substr($File_Name, strrpos($File_Name, '.')); //get file extention
            $Random_Number      = rand(0, 9999999999); //Random number to be added to name.
            $NewFileName 		= $Random_Number.$File_Ext; //new file name
        
            if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
            {
                die('Success! File Uploaded.');
            }else{
                die('error uploading File!');
            }
        
        }
        else
        {
            die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
        }







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值