首页 > 解决方案 > CodeIgniter file upload error “You did not select a file to upload” using Ajax

问题描述

I've seen and tried a few answers that are similar to this question, but it still displays the same error.

The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)

My view:

<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
    <label for="fldFileName" class="col-sm-4 control-label">Image</label>
    <div class="col-sm-8">
        <input type="file" name="fldFileName" value="" class="form-control" id="fldFileName"  />
    </div>
  </div>
 <button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>

javascript to submit form:

        $(document).on("click", "#newSensorSubmit", function(event){   
            var posturl="<?php echo site_url("sensors/add_deployment");?>";
            var formData = new FormData();

            var fldFileName = $('#fldFileName').val(); 
            formData.append('fldFileName', fldFileName);
            jQuery.ajax({
                url: posturl,
                data: formData,
                cache: false,
                mimeType: "multipart/form-data",
                dataType: 'json',
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                     if(data.status === 'success') {
                         //handle success
                    }
                        else {
                         //handle fail
                        }
                    },
                error: (error) => {
                $('#articleErrorText').html(JSON.stringify(error));
                   }
                });   
        });

controller:

public function add_deployment(){
    $this->load->helper(array('form', 'url'));
    $this->load->library('upload');
    $config = array(
            'upload_path' => site_url("attachments/project/999/metstations"),
            'allowed_types' => "gif|jpg|png|jpeg",
            'overwrite' => TRUE,
            'max_size' => "16000000" 
            );
    $this->load->library('upload', $config);
        
    if($this->upload->do_upload('fldFileName'))
        {
            $data['image_metadata'] = array('image_metadata' => $this->upload->data());      
        }
        else
        {
            $error = $this->upload->display_errors();
            $data['errors']='<p class="error-message">'.$error.'</p>';
            $data['status']='failure';
            }

}

标签: javascriptjqueryajaxcodeigniter

解决方案


Try This.

To get all your form inputs, including the type="file" you need to use FormData object.

To append param just use append() method:

formData.append("param", "value");

And in the php-side I catch it:

echo $file_name = ($_FILES['file']['name']);

View Code:-

<body>
        <p id="msg"></p>
        <input type="file" id="file" name="file" />
        <button id="upload">Upload</button>
</body>

jQuery / Ajax Code:-

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function(e){
    $('#upload').on('click', function () {
        var file_data = $('#file').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajax({
            url: 'ControllerName/upload_file', // point to server-side controller method
            dataType: 'text', // what to expect back from the server
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
                $('#msg').html(response); // display success response from the server
            },
            error: function (response) {
                $('#msg').html(response); // display error response from the server
            }
        });
    });
});
</script>

Controller Code:-

class ControllerName extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

 
    function upload_file() {

        //upload file
        $config['upload_path'] = 'uploads/';
        $config['allowed_types'] = '*';
        $config['max_filename'] = '255';
        $config['encrypt_name'] = TRUE;   // remove it for actual file name.
        $config['max_size'] = '1024'; //1 MB

        if (isset($_FILES['file']['name'])) {
            if (0 < $_FILES['file']['error']) {
                echo 'Error during file upload' . $_FILES['file']['error'];
            } else {
                if (file_exists('uploads/' . $_FILES['file']['name'])) {
                    echo 'File already exists : uploads/' . $_FILES['file']['name'];
                } else {
                    $this->load->library('upload', $config);
                    if (!$this->upload->do_upload('file')) {
                        echo $this->upload->display_errors();
                    } else {
                        echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
                    }
                }
            }
        } else {
            echo 'Please choose a file';
        }
    }

}

Note:- For more reference regarding this check this

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append


推荐阅读