简体   繁体   English

无法使用 AJAX Codeigniter 上传图片

[英]Cannot upload image using AJAX Codeigniter

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.我正在尝试将图像上传到 phpmyadmin 数据库并选择 BLOB 类型用于数据库中的图像存储,我正在尝试使用 jQuery 上传图像但问题是我的new FormData(this)不是表单中的任何值,并且由于进入控制器功能后,如果不进入if condition并移向 else 并在发生某些错误时返回响应。

I have tried many different ways to pass the data but none of them is working:我尝试了许多不同的方法来传递数据,但都没有奏效:

  • data: new FormData(this) ,数据: new FormData(this)
  • data: new FormData($('#upload_image')[0]) ,数据: new FormData($('#upload_image')[0]) ,
  • data: { fileName: $("input[name='imageFile']").val().split("\\\\").pop() }数据: { fileName: $("input[name='imageFile']").val().split("\\\\").pop() }
  • data: { file: $("input[name='imageFile']").val() }数据: { 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);
        }
    }

In your data variable, you are referencing the wrong form ID.在您的数据变量中,您引用了错误的表单 ID。

It should be它应该是

data: new FormData($('#upload_image')[0]),

在您的 ajax 配置中,您应该将processData设置为false以防止数据值转换为查询字符串:

                    processData: false,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM