【问题标题】:Using uploader.php class to handle multiple file upload using php and jquery使用 uploader.php 类处理使用 php 和 jquery 的多个文件上传
【发布时间】:2015-05-30 08:44:00
【问题描述】:

我想使用link 中的答案使用uploader.php 类上传多个pdf 文件。

我正在使用 jquery 和 php。下面是我的代码,现在我想使用链接中的上传器类来处理和上传文件。

使用此代码,我在 uploader.php 的第 70 行和第 71 行得到未定义的索引 txtFile

上传者类是

<?php

    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
        private $seqnence;
        public $name='Uploader';
        public $useTable    =false;

        function setDir($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }

        function allowAllFormats(){
            $this->allowAll =   true;
        }

        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }

        function setExtensions($options){
            $this->extensions   =   $options;
        }

        function setSameFileName(){
            $this->sameFileName =   true;
            $this->sameName =   true;
        }
        function getExtension($string){
            $ext    =   "";
            try{
                    $parts  =   explode(".",$string);
                    $ext        =   strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext    =   "";
            }
            return $ext;
    }

        function setMessage($message){
            $this->errorMessage =   $message;
        }

        function getMessage(){
            return $this->errorMessage;
        }

        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
            $this->imageSeq =   $seq;
    }

    function getRandom(){
        return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
    }
    function sameName($true){
        $this->sameName =   $true;
    }
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){

        if($this->sameName==false){
                    $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
            $this->uploadName=  $name;
        }
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }

        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }

    }

?>

    $(document).ready(function(){  
        $("#add_more").click(function(e){  
        	var current_count = $('input[type="file"]').length;
        	var next_count = current_count + 1;
        	$('#file_upload').append('<div class="col-md-3"><input class="form-control" type = "file" name = "file_'+next_count+ '"/></div> ');
        	
        });  
    });  
!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<link rel="stylesheet" type="text/css" href="../bootstrap-3.3.4-dist/css/bootstrap.min.css" />
		<link rel="stylesheet" type="text/css" href="../bootstrap-datetimepicker-master/build/css/bootstrap-datetimepicker.min.css" />
		<link href="includes/Styles/style_boot.css" rel="stylesheet">
		<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
		<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
		<!--[if lt IE 9]>
		<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
		<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
		<![endif]-->

	</head>
	<body>
	
		<?php echo $header; ?>
		<hr />
		<div class="container">
			<div class="col-md-8">
			<?php
			
			if(Session::exists('home')){
				
			echo  Session::flash('home') ;
			}
			
			?>			
		</div>
		<hr />
		<div class="container">
				<form id="file_upload" action="upload_file.php"  method="get" enctype="multipart/form-data">
					<div class="row">
						<div  class="col-md-3 ">
							<input class="form-control" type="file" name="file_1">
						</div>
					</div><br>
					<div class="row">
							<div  class="col-md-3">
								<a id="add_more" href="#">Add More Files</a>
							</div>
						
						<div class="col-md3">
							<input class="btn-success" type="submit" value="upload" />
						</div>
					</div>

				</form>
			</div>
			</div>
		<hr />
	<?php echo $footer; ?>
	
	<script type="text/javascript" src="../jquery/jquery-2.1.4.js"></script>
	<script type="text/javascript" src="includes/common/ext.js"></script>
	<script type="text/javascript" src="../bootstrap-3.3.4-dist/js/bootstrap.js"></script>
	</body>
</html>

我想用这段代码来处理 php 中的文件,但是我应该用什么来代替这一行中的 txtFile "if($uploader->uploadFile('txtFile'))";

<?php
$uploader   =   new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
$uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){   //txtFile is the filebrowse element name //     
    $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
    $uploader->getMessage(); //get upload error message 
}


?>

【问题讨论】:

  • 抱歉,请在上方编辑您的问题(下方有一个edit 按钮)并在文本开头修复您要发布的链接。此外,我无法在您发布的代码中发现您引用的类定义,那么我们该如何提供帮助?您希望我们如何猜测您未发布的代码中的第 70 行和第 71 行是什么?
  • 我很抱歉缺少链接。
  • uploader.php 类在链接中。我正在编辑它。

标签: php jquery file-upload


【解决方案1】:

未定义的错误是因为您要访问未初始化的变量。之前检查一下:

if(isset($var))

要访问已发布的文件,请使用以下内容:

foreach($_FILES as $key => $info) {
    if(substr($key, 0, 5) != "file_")
        continue;
    // Handle the file - file information at $info as array
}

或者在你的文件输入中使用multiple标签——那么你甚至可以选择多个文件:

<input class="form-control" type="file" name="files[]" multiple>

那么它在 PHP 中是这样工作的:

foreach($_FILES['files'] as $file) {
    // Handle the file - file information at $file as array
}

【讨论】:

  • 1.在 print_r($_FILES) 的情况下是否必须使用 foreach 循环。
  • 2. var_dump($_FILES) 给出数组(0){}
  • var_dump($_FILES) 给出一个空数组?这很疯狂,因为您在表单中使用了正确的 enctype。它什么时候给出一个空数组?即使您只提交一个文件?
  • 是的,Richard 它在单个文件和多个文件的两种情况下都给出了一个空数组。
【解决方案2】:

你的方法是get它应该是POST,你的文件上传字段的名称是file_1但是你尝试通过txtFile访问文件。

【讨论】:

  • 这就是我想问的,我应该用什么来代替 txtFile。
  • 我仅将 GET 用于测试目的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 2010-12-29
  • 1970-01-01
  • 2012-05-22
  • 2012-06-11
  • 1970-01-01
  • 2021-09-09
相关资源
最近更新 更多