0

I'm trying to upload image to phpmyadmin database and have select BLOB type for image storage in database, I'm trying to upload image using jQuery but the issue is that my new FormData(this) is not any values in the form and due to that after going in the controller function if doesn't goes in if condition and moves towards else and returns the response as some error has occurred.

I have tried many different ways to pass the data but none of them is working:

  • data:new FormData(this),
  • data: new FormData($('#upload_image')[0]),
  • data: { fileName: $("input[name='imageFile']").val().split("\\").pop() }
  • data: { file: $("input[name='imageFile']").val() }

My View

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $title; ?></title>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap-grid.min.css">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap-reboot.min.css">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css">
    <script src="https://use.fontawesome.com/e26d097cd9.js"></script>

</head>
<body>
    <div class="container">
        <br><br><br>
        <h3 class="text-center">Uploading Image Using AJAX</h3>
        <div id="message"></div>
        <form method="POST" id="upload_image" enctype="multipart/form-data">
            <input type="file" name="imageFile" id="image_file">
            <br><br>
            <button type="submit" class="btn btn-info" name="upload" id="upload">Upload </button>
        </form>
        <div class="uploaded_image">

        </div>
    </div>

    <!-- <script type="text/javascript" src="<?php echo base_url(); ?>assets/bootstrap/js/jquery.js"></script> -->
    <script type="text/javascript" src="<?php echo base_url(); ?>assets/bootstrap/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js"></script>

    <script type="text/javascript">
        $('#upload_image').submit(function(e){
        // $('#upload_image').on('submit', function(e){
            e.preventDefault();
            // var formData = $('#uploaded_image').serialize();
            // alert(formData);
            if($('#image_file').val() == ''){
                alert('Please Attach a File');
            }
            else{
                // alert("Hello");
                $.ajax({
                    url: "<?php echo base_url(); ?>main/ajax_upload",
                    type: "POST",
                    // data:new FormData(this),
                    data: new FormData($('#upload_image')[0]),
                    // data: {
                    //  fileName: $("input[name='imageFile']").val().split("\\").pop(),
                    //  // file: $("input[name='imageFile']").val()
                    // },
                    // data: new FormData($('#upload_image')[0]),
                    contentType: false,
                    cache: false,
                    processType: false,
                    dataType: 'JSON',
                    beforeSend: function(){
                        $('#upload').append('<i class="fa fa-spinner fa-spin"></i>');
                    },
                    success: function(data){
                        $('#upload .fa-spinner').remove();
                        $('#uploaded_image').html(data);

                        $('#message').html(data.message);
                    }
                });
            }
        });
    </script>
</body>
</html>

My Controller

public function ajax_upload(){
        // echo "<script>alert('hello')</script>";
        if(isset($_FILES['image_file']["name"])){
        // if(isset($_FILES['imageFile'])){
            $config['upload_path'] = './upload/'; 
            $config['allowed_types'] = 'jpg|jpeg|png|gif';

            $this->load->library('upload', $config);

            if(!$this->upload->do_upload('imageFile')){
                // echo $this->upload->display_errors();
                $error['message'] = $this->upload->display_errors();
                echo json_encode($error);
            }
            else{
                $data = $this->upload->data();
                // echo "<img src=" . base_url() . "upload/" . $data["file_name"] . ">";
                echo '<img src="'.base_url().'upload/'.$data["file_name"].'">';
            }
        }
        else{
            $error['message'] = "An Error Occured";
            echo json_encode($error);
        }
    }

2 Answers 2

1

In your data variable, you are referencing the wrong form ID.

It should be

data: new FormData($('#upload_image')[0]),
Sign up to request clarification or add additional context in comments.

1 Comment

Ooh sorry that's my mistake! Thanks for letting me know but now my control in not being transferred to my control and I'm getting an error of "Uncaught TypeError: Illegal invocation" in console.
1

On your ajax config, you should set the processData to false to prevent the data values getting converted to a query string :

                    processData: false,

5 Comments

Ok! so now i can pass my data but when i'm debugging my code so form network section I'm getting (binary) as the passed file.
I think the problem is you set the input name as imageFile but on the controller you get the file using $_FILES['image_file'], the name is different
Thank for pointing out the mistake and now i'm really close to the solution but the problem is that now it is providing me an error that 'The upload path does not appear to be valid'. but my upload path is valid. I tried using $config['upload_path'] = './upload/'; also but the same error is provided again and again.
If you have the upload folder outside CI application folder (in root folder), you could use FCPATH like this : $config['upload_path'] = realpath(FCPATH . 'upload');, and if the upload folder is inside the application folder, you could use APPPATH like : $config['upload_path'] = realpath(APPPATH . 'upload');
It's placed in the root folder where application, system and folders are present; and I have used base_url() . 'upload' and FCPATH . 'upload' and I print the whole file path it prints the correct file path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.