CodeIgniter - Ajax文件上传 - 不上传文件

时间:2015-09-29 08:24:42

标签: php jquery ajax codeigniter file-upload

我在bootstrap模式窗口中有一个表单,我在其中上传了一些文件。

这是我的剧本

<?php

/**
 * Handle the file uploading for the article
 */
public function upload_ajax() {
    $this->output->enable_profiler(false);

    // check if the article has been created
    if (!$this->input->post('post_id')) {
        // do something here ..
    } else {
        // set upload configs
        $dir = FCPATH . '/posts';
        $config = array(
            'upload_path' => $dir,
            'allowed_types' => 'gif|jpg|png',
            'max_width' => '1024',
            'max_height' => '768',
        );
        $this->load->library('upload', $config);

        // try to upload the file
        if (!$this->upload->do_upload('userfile')) {
            $response = array(
                'status' => '400',
                'message' => $this->upload->display_errors(),
            );
        } else {
            $data = $this->upload->data();
            $response = array(
                'status' => '200',
                'message' => '<p>The image uploaded successfully</p>',
            );
        }
    }

    $this->output->set_content_type('application/json', 'utf-8')
        ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))->_display();
    exit();
}

javascript

$('#btn-upload').on('click', function (event) {
  event.preventDefault();

  $.ajax({
    url : url, // the value from the form action attribute
    type : 'post',
    data : {
      'post_id' : $('[name="postID"]').val(),
      'userfile' : $('[name="userfile"]').val(),
      'name' : $('[name="userfile"]').attr('name'),
    },
    dataType : 'json',
    success : function(response) {
      $('#upload-results').removeClass('alert alert-success alert-danger').html('');

      if (response.status == 200) {
        $('.upload-form').hide();
        $('#upload-results').addClass('alert alert-success').html(response.message);
      }

      if (response.status == 400) {
        $('.upload-form').show();
        $('#upload-results').addClass('alert alert-danger').html(response.message);
      }
    },
  });
});

和视图

<div class="modal-body">
    <div id="upload-results"></div>

    <?php echo form_open_multipart('posts/upload_ajax', array('class' => 'form-horizontal upload-form')); ?>

    <input type="hidden" name="postID"/>

    <div class="form-group">
        <label class="col-sm-3 control-label">Image Upload</label>
        <div class="col-sm-5">
            <div data-provides="fileinput" class="fileinput fileinput-new">
                <input type="hidden">

                <div data-trigger="fileinput" style="width: 200px; height: 150px;" class="fileinput-new thumbnail">
                    <img src="<?php echo base_url('img/default.jpg'); ?>">
                </div>
                <div style="max-width: 200px; max-height: 150px; line-height: 6px;" class="fileinput-preview fileinput-exists thumbnail"></div>
                <div> 
                    <span class="btn btn-white btn-file"> 
                        <span class="fileinput-new">Select image</span> 
                        <span class="fileinput-exists">Change</span> 
                        <input type="file" accept="image/*" name="userfile"/> 
                    </span>
                    <a data-dismiss="fileinput" class="btn btn-orange fileinput-exists" href="#">Remove</a>
                </div>
            </div>
        </div>
    </div>
    <?php echo form_close(); ?>
</div><!-- /.modal-body -->

问题是,即使我选择了图像,我也总是会收到上传库中的验证错误"You did not select a file to upload"。但是在firebug上我可以看到我用ajax请求发送的3个变量

'post_id' : $('[name="postID"]').val(), // shows e.g. 12
'userfile' : $('[name="userfile"]').val(), // shows e.g. my-image.jpg
'name' : $('[name="userfile"]').attr('name'), // shows userfile

我也试过这个

$userfile = $this->input->post('name');
if (!$this->upload->do_upload($userfile))

但没有运气。我怎样才能正常工作?

1 个答案:

答案 0 :(得分:0)

您发送的文件我们在ajax中使用formData

var formData = new FormData(this);
$.ajax({
                url : url, // the value from the form action attribute
                type : 'post', 
                data : formData
                cache: false,
                contentType: false,
                processData: false,
        dataType : 'json',
                success : function(response) {
                    $('#upload-results').removeClass('alert alert-success alert-danger').html('');

                    if (response.status == 200) {
                        $('.upload-form').hide();
                        $('#upload-results').addClass('alert alert-success').html(response.message);
                    }

                    if (response.status == 400) {
                        $('.upload-form').show();
                        $('#upload-results').addClass('alert alert-danger').html(response.message);
                    }
                },
            });

在php端检查值

print_r($_POST);
print_r($_FILES);