上传文件使用AJAX& CodeIgniter 3.0.1

时间:2015-10-05 14:15:44

标签: javascript php jquery ajax codeigniter

请好好..

我已经两天了,所以我决定发布它。

我有什么:

我的localhost(Windows)上安装了一个新的CodeIgniter,带有一个控制器和一个视图。一切都很完美。

我想做什么:

使用带有CodeIgniter的AJAX上传图像,而无需重新加载页面。

我的控制器(Test.php):

class Test extends CI_Controller {
   public function index()
   {
        # Started working with file upload.
        $validFiles = array(
            'upload_path'   => './assets',
            'allowed_types' => 'jpg|png|gif',
            'max_size'      => 250000
        );
        $this->load->library('upload', $validFiles);
        if ($this->upload->do_upload('newsphoto'))
        {
            echo "Image Uploaded Successfully!";
        }
        else
        {
            echo $this->upload->display_errors();
        }

   }

   public function upload()
   {
      $this->load->helper('form');
      $this->load->view('test');
   }
}

我的观点(test.php):

<html>
<body>

<div class="CustomForm">
    <?php echo form_open_multipart(base_url().'test', array('class' => 'newsForm')); ?>
    <div class="row">
        <input type="file" class="InputField" name="newsphoto" value="">
        <input type="text" class="InputField" name="title" value="">
        <textarea name="news" class="InputField" cols="30" rows="10"></textarea>
        <button>Go</button>
    </div>
    <?php form_close(); ?>
</div> 
</body>
<html>

我的JS脚本(在视图中我将其分开以便于阅读):

<script type="text/javascript">
           $(document).ready(function () {
               var form = $('form.newsForm');
               form.on('submit', function (c) {
                   c.preventDefault();

                   var data = new FormData();
                   $.each($('form.newsForm :input'), function(i, fileds){
                       data.append($(fileds).attr('name'), $(fileds).val());
                   });
                   $.each($('form.newsForm input[type=file]')[0].files, function (i, file) {
                       data.append(file.name, file);
                   });
                   $.ajax({
                       url: '<?php echo base_url(); ?>/test',
                       data: data,
                       cache: false,
                       contentType: false,
                       processData: false,
                       type: 'POST',
                       success: function (c) {
                           var msg = $('div.jsMessage');
                           msg.empty();
                           msg.html(c);
                       }
                   });
                   return false;
               });
           })
</script>

我现在得到的是什么:

我正在进行一次正常的上传工作,如图所示。 Upload result

我认为我的ajax代码没有运行,而且我不确定它是否会起作用。有什么帮助吗?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

尝试Ajax文件上传器:github

您可以在下面找到适用于您的方案的工作示例。

<强> routes.php文件

$route['form'] = 'Test/upload';
$route['upload'] = 'Test';

<强>的config.php

  

提到的代码有助于维护localhost和live服务器的基本URL配置。将文件移动到实时服务器时,您不必更新$config['base_url']。你可以在下面找到这段代码。

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url']    = "$root";

autoload.php

$autoload['helper'] = array('url');

控制器 - Test.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

    class Test extends CI_Controller
    {
        public function index()
        {
            # Started working with file upload.
            $validFiles = array(
                'upload_path'   => 'assets',
                'allowed_types' => 'jpg|png|gif',
                'max_size'      => 250000
            );
            $this->load->library('upload', $validFiles);
            if ($this->upload->do_upload('newsphoto'))
            {
                $return['msg']='Image Uploaded Successfully!';
                echo json_encode($return);


            }
            else
            {
                echo $this->upload->display_errors();
            }

        }

        public function upload()
        {
            $this->load->helper('form');
            $this->load->view('test');
        }
   }

查看: test.php

  

您在视图中使用过jquery库吗?使用它会使JS工作。

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="<?php echo base_url() ?>assets/JS/ajaxfileupload.js"></script>
</head>
<body>
<div class="CustomForm">
    <?php echo form_open_multipart(base_url().'index.php/upload', array('class' => 'newsForm')); ?>
    <div class="row">
        <input type="file" id="newsphoto" class="InputField" name="newsphoto" value="">
        <input type="text" id="title" class="InputField" name="title" value="">
        <textarea name="news" id="news" class="InputField" cols="30" rows="10"></textarea>
        <button> Upload</button>
    </div>
    <?php form_close(); ?>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        var form = $('form.newsForm');
        form.on('submit', function (c) {
            c.preventDefault();

            var data = new FormData();
            $.each($('form.newsForm :input'), function(i, fileds){
                data.append($(fileds).attr('name'), $(fileds).val());
            });
            $.each($('form.newsForm input[type=file]')[0].files, function (i, file) {
                data.append(file.name, file);
            });

            var param = {'title':$('#title').val(),'news':$('#news').val()};

            $.ajaxFileUpload
            (

                {
                    url:'<?php echo base_url(); ?>index.php/upload',
                    secureuri:false,
                    data: param,
                    fileElementId:'newsphoto',
                    dataType: 'json',
                    beforeSend: function(){
                        console.log("I'm sending AJAX.");
                        //display loading?
                    },
                    success: function (data, status)
                    {
                        alert(data.msg);
                    },
                    error: function (data, status, e)
                    {
                        alert(e);
                    }
                }
            );
            return false;
        });
    });
</script>

</body>
<html>