使用PHP-CodeIgniter上传的AJAX文件不起作用

时间:2016-01-30 08:45:36

标签: php jquery ajax codeigniter

我一直在尝试使用AJAX上传图片,但不知怎的,它无法正常工作。 CodeIgniter总是抛出你没有选择任何文件'。 提前谢谢。

这是我的控制器 -     

class Upload extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('upload/upload');
    }

    public function upload_file() {
        $config['upload_path'] = './uploads/Ajax/';
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;

        $this->load->library('upload', $config);
        $title=$this->input->post('title');

        if (!$this->upload->do_upload('userfile')) {
            echo $this->upload->display_errors()."<br>".$title;
        }
        else {
            $data = $this->upload->data();
            echo $data['file_name']." uploaded successfully";
        }
    }
}

/* end of file */

这是视图

<!DOCTYPE HTML>
<html>
    <head>
        <title>AJAX File Upload</title>
        <script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js">    </script>
        <script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js">    </script>
        <script>
            $(document).ready(function() {
                $('#upload-form').submit(function(e) {
                    e.preventDefault();
                    if (typeof FormData !== 'undefined') {
                        $.ajax({
                            url     :   '<?php echo base_url(); ?>upload/upload/upload_file',
                            type    :   'POST',
                            data    :   FormData,
                            beforeSend: function () {
                                $("#result").html("Uploading, please wait....");
                            },
                            error: function () {
                                alert("ERROR in upload");
                            },
                            success :   function(data) {
                                $('#result').html(data)
                            }
                        });
                    }
                    else {
                        alert("Your browser doesn't support FormData API!");
                    }
                });
            });
        </script>
    </head>

<body>
    <h1>Upload File</h1>
    <form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
        <p>
            <label for="title">Title</label>
            <input type="text" name="title" id="title" value="" autocomplete="off">
        </p>
        <p>
            <label for="userfile">File</label>
            <input type="file" name="userfile" id="userfile">
        </p>
        <input type="submit" name="submit" id="submit">
    </form>

    <h2>Result</h2>
    <span id="result"></span>
</body>

我在Firefox 43,IE11&amp; Chrome 43

5 个答案:

答案 0 :(得分:1)

<script>
        $(document).ready(function() {
            $('#upload-form').submit(function(e) {
                e.preventDefault();
                if (typeof FormData !== 'undefined') {
                    $.ajax({
                        url     :   '<?php echo base_url(); ?>upload/upload/upload_file',
                        type    :   'POST',
                         secureuri      :false,
                       fileElementId    :'userfile',
                        data    :   FormData,
                        beforeSend: function () {
                            $("#result").html("Uploading, please wait....");
                        },
                        error: function () {
                            alert("ERROR in upload");
                        },
                        success :   function(data) {
                            $('#result').html(data)
                        }
                    });
                }
                else {
                    alert("Your browser doesn't support FormData API!");
                }
            });
        });
    </script>

答案 1 :(得分:0)

你可以使用

$(document).on('submit','#form_id',function(){
   var formData = new FormData(this);
   $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
            console.log(data);
        }
    });
});

这不需要插件,为了方便您可以使用ajaxForm jquery插件并使用

$('#form-id').ajaxSubmit({
   // same config as ajax call but dont use data option right here
}); 

查看http://malsup.com/jquery/form/以获取有关插件的更多信息

答案 2 :(得分:0)

您需要在ajax请求中添加xhr函数

$(document).on('submit','#form_id',function(){
   var formData = new FormData(this);
   $.ajax({
        type:'POST',
        xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();            
            return xhrobj;
        },
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
            console.log(data);
        }
    });
});

答案 3 :(得分:0)

使用此

$("#upload-form").on('submit' ,function(){
    var form = $(this);
    $.ajax({
        url: form.attr('action'),
        data: new FormData(form[0]),
        dataType: 'json',
        method: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){


        }
    });
});

答案 4 :(得分:0)

使用$ .ajaxFileUpload而不是$ .ajax,这应该可行,如果没有请让我看看你的AjaxFileUpload.js

$(document).ready(function() {
                $('#upload-form').submit(function(e) {
                    e.preventDefault();
                    if (typeof FormData !== 'undefined') {

                       $.ajaxFileUpload({ 
                        url             :'./upload/upload_file/',                  
                        fileElementId   : 'userfile', //  your input file ID
                        dataType        : 'json',
                        // 
                        data            : {
                            'title'             : $('#title').val() // parse title input data
                        },
                            beforeSend: function () {
                                $("#result").html("Uploading, please wait....");
                            },
                            error: function () {
                                alert("ERROR in upload");
                            },
                            success :   function(data) {
                                $('#result').html(data)
                            }
                        });
                    }
                    else {
                        alert("Your browser doesn't support FormData API!");
                    }
                });
            });