【问题标题】:CodeIgniter - Ajax file upload - not uploading the fileCodeIgniter - Ajax 文件上传 - 不上传文件
【发布时间】:2015-12-26 15:40:20
【问题描述】:

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

这是我的脚本

<?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"。但是在萤火虫上,我可以看到我通过 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))

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

【问题讨论】:

    标签: php jquery ajax codeigniter file-upload


    【解决方案1】:

    您发送的文件我们在 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);
    

    【讨论】:

    • 我也需要这些吗? cache: falsecontentType: falseprocessData: false,还是可选的?
    • 我在 firebug 上收到此错误:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement. 指向 var formData = new FormData(this);
    • ok,试试var form = $('form')[0]; var formData = new FormData(form);
    • 您能否在另一件事上给我一些额外的帮助?我打算使用引导进度条来显示上传进度,但我不知道该怎么做
    • 我对bootstarp不太了解!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 2012-07-18
    • 2017-10-22
    • 1970-01-01
    • 2016-04-16
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多