【问题标题】:how to implement an upload script with codeigniter如何使用 codeigniter 实现上传脚本
【发布时间】:2011-06-02 19:21:52
【问题描述】:

我正在尝试为 codeigniter 实现一个多文件上传脚本。脚本可以在这里找到 http://valums.com/ajax-upload/。我觉得很好,所以我决定把当前的应用程序。

问题是,我无法使用 codeigniter 访问上传的文件。如果您是 codeigniter 开发人员,请告知我如何获取脚本发送的文件?

【问题讨论】:

  • 还有 rurunforest,你应该添加更多信息。
  • @Ipalaus 谢谢,我不知道我应该这样做,只是勾选了 Vs

标签: php javascript codeigniter file-upload


【解决方案1】:

CodeIgniter 有几种处理上传的方法,但由于您的 ajax-upload 脚本已经有一个处理程序,您应该使用它。

如何:

在您的应用程序/库文件夹中创建一个名为 Qqfileuploader.php 的新文件并将其粘贴到其中:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    class Qqfileuploader {
        private $allowedExtensions = array();
        private $sizeLimit = 10485760;
        private $file;

        function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
            $allowedExtensions = array_map("strtolower", $allowedExtensions);

            $this->allowedExtensions = $allowedExtensions;        
            $this->sizeLimit = $sizeLimit;

            $this->checkServerSettings();       

            if (isset($_GET['qqfile'])) {
                $this->file = new qqUploadedFileXhr();
            } elseif (isset($_FILES['qqfile'])) {
                $this->file = new qqUploadedFileForm();
            } else {
                $this->file = false; 
            }
        }

        private function checkServerSettings(){        
            $postSize = $this->toBytes(ini_get('post_max_size'));
            $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        

            if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
                $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
                die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
            }        
        }

        private function toBytes($str){
            $val = trim($str);
            $last = strtolower($str[strlen($str)-1]);
            switch($last) {
                case 'g': $val *= 1024;
                case 'm': $val *= 1024;
                case 'k': $val *= 1024;        
            }
            return $val;
        }

        /**
         * Returns array('success'=>true) or array('error'=>'error message')
         */
        function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
            if (!is_writable($uploadDirectory)){
                return array('error' => "Server error. Upload directory isn't writable.");
            }

            if (!$this->file){
                return array('error' => 'No files were uploaded.');
            }

            $size = $this->file->getSize();

            if ($size == 0) {
                return array('error' => 'File is empty');
            }

            if ($size > $this->sizeLimit) {
                return array('error' => 'File is too large');
            }

            $pathinfo = pathinfo($this->file->getName());
            $filename = $pathinfo['filename'];
            //$filename = md5(uniqid());
            $ext = $pathinfo['extension'];

            if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
                $these = implode(', ', $this->allowedExtensions);
                return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
            }

            if(!$replaceOldFile){
                /// don't overwrite previous files that were uploaded
                while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                    $filename .= rand(10, 99);
                }
            }

            if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
                return array('success'=>true);
            } else {
                return array('error'=> 'Could not save uploaded file.' .
                    'The upload was cancelled, or server error encountered');
            }

        }    
    }

现在,在您要上传到的控制器中,执行以下操作:

// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;

$this->load->library("Qqfileuploader",array($allowedExtensions, $sizeLimit));
$this->Qqfileuploader->handleUpload('uploads/');
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

应该工作。

【讨论】:

    【解决方案2】:

    实际上 CodeIgniter 库似乎只允许将 1 个参数传递给构造函数。所以 Adrian Gonzales 的代码对我来说不太适用 - 我必须更改构造函数以将参数作为单个数组接受(如此处所述:http://codeigniter.com/user_guide/general/creating_libraries.html)。然后就成功了。

    这是我的图书馆代码:

        <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    
    class qqFileUploader {
        private $allowedExtensions = array();
        private $sizeLimit = 10485760;
        private $file;
    
        function __construct($params = array()){
            $allowedExtensions = $params['allowedExtensions'];
            $sizeLimit = $params['sizeLimit'];
    
            $allowedExtensions = array_map("strtolower", $allowedExtensions);
    
            $this->allowedExtensions = $allowedExtensions;        
            $this->sizeLimit = $sizeLimit;
    
            $this->checkServerSettings();       
    
            if (isset($_GET['qqfile'])) {
                $this->file = new qqUploadedFileXhr();
            } elseif (isset($_FILES['qqfile'])) {
                $this->file = new qqUploadedFileForm();
            } else {
                $this->file = false; 
            }
        }
    
        private function checkServerSettings(){        
            $postSize = $this->toBytes(ini_get('post_max_size'));
            $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
    
            if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
                $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
    
                die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
            }        
        }
    
        private function toBytes($str){
            $val = trim($str);
            $last = strtolower($str[strlen($str)-1]);
            switch($last) {
                case 'g': $val *= 1024;
                case 'm': $val *= 1024;
                case 'k': $val *= 1024;        
            }
            return $val;
        }
    
    
        function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
            if (!is_writable($uploadDirectory)){
                return array('error' => "Server error. Upload directory isn't writable.");
            }
    
            if (!$this->file){
                return array('error' => 'No files were uploaded.');
            }
    
            $size = $this->file->getSize();
    
            if ($size == 0) {
                return array('error' => 'File is empty');
            }
    
            if ($size > $this->sizeLimit) {
                return array('error' => 'File is too large');
            }
    
            $pathinfo = pathinfo($this->file->getName());
            //$filename = $pathinfo['filename'];
            $filename = md5(uniqid());
            $ext = $pathinfo['extension'];
    
            if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
                $these = implode(', ', $this->allowedExtensions);
                return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
            }
    
            if(!$replaceOldFile){
                /// don't overwrite previous files that were uploaded
                while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                    $filename .= rand(10, 99);
                }
            }
    
            if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
                return array('success'=>true, 'fileName' => $filename . '.' . $ext);
            } else {
                return array('error'=> 'Could not save uploaded file.' .
                    'The upload was cancelled, or server error encountered');
            }
    
        }    
    }
    
    
    class qqUploadedFileXhr {
    
        function save($path) {    
            $input = fopen("php://input", "r");
            $temp = tmpfile();
            $realSize = stream_copy_to_stream($input, $temp);
            fclose($input);
    
            if ($realSize != $this->getSize()){            
                return false;
            }
    
            $target = fopen($path, "w");        
            fseek($temp, 0, SEEK_SET);
            stream_copy_to_stream($temp, $target);
            fclose($target);
    
            return true;
        }
        function getName() {
            return $_GET['qqfile'];
        }
        function getSize() {
            if (isset($_SERVER["CONTENT_LENGTH"])){
                return (int)$_SERVER["CONTENT_LENGTH"];            
            } else {
                throw new Exception('Getting content length is not supported.');
            }      
        }   
    }
    
    
    class qqUploadedFileForm {  
        /**
         * Save the file to the specified path
         * @return boolean TRUE on success
         */
        function save($path) {
            if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
                return false;
            }
            return true;
        }
        function getName() {
            return $_FILES['qqfile']['name'];
        }
        function getSize() {
            return $_FILES['qqfile']['size'];
        }
    }
    

    【讨论】:

    • 如何在同一个库中添加 qqUploadedFileXhr() 和 qqUploadedFileForm() 类?
    • 非常感谢。我通过在单独的库文件 Lolzz 中分离每个类来做到这一点
    【解决方案3】:

    花很多时间去/server/php.php文件:https://github.com/valums/file-uploader/blob/master/server/php.php

    你必须在你的控制器上重现类似的东西来处理 ajax 脚本的 XMLHttpRequest。

    【讨论】:

      【解决方案4】:

      我找到了一个非常简单的解决方案。

      首先,转到脚本,编辑查询字符串变量,以便生成分段 uri。

      然后在控制器中,我使用 file_get_contents("php://input") 来获取内容。 要获取文件名,只需 $this->input->uri(3);

      【讨论】:

        猜你喜欢
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-16
        • 1970-01-01
        相关资源
        最近更新 更多