如何在codeigniter中使用ajax上传文件

时间:2022-11-24 12:20:53

I am trying to upload a file along with other parameters using ajax. However, the files are not getting uploaded.

我正在尝试使用ajax上传一个文件和其他参数。然而,这些文件并没有被上传。

Form Code

形式的代码

<form id="first_form" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" accept="image/*" onchange="loadFile(event)">
    <input type="text" data-validation="url" class="form-control" id="first_name" name="first_name" placeholder="First Name" />
    <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" />  
    <input type="image" src="<?php echo base_url(); ?>assets/images/icon/_Save.png" class="Save-container img-circle" id="submit_first_form">
</form>

Script Code

脚本代码

<script type="text/javascript">
  $(document).ready(function() {
    $("#submit_first_form").click(function(event) {
    event.preventDefault();
    var file = $("input#file").val(); 
    var first_name = $("input#first_name").val();
    var last_name = $("input#last_name").val();

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>" + "student/add_data",
        dataType: 'json',
        data: {
            file: file, 
            first_name: first_name,
            last_name: last_name
        },
        success: function(res) {
        if (res)
            {
                console.log(res);
            }
        }
    }); }); });
</script>

Controller Code

控制器代码

public function add_data()
    {
        $data = array(
            'file' => $this->input->post('file'),
            'first_name' => $this->input->post('first_name'),
            'last_name'=>$this->input->post('last_name')
        );

        $status = "";
        $msg = "";
        $file_element_name = $data['file'];

        $config['upload_path'] = 'www.localhost.com/project/assets/supplier';
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;
        $config['encrypt_name'] = TRUE;

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

        if (!$this->upload->do_upload($file_element_name))
            {
                $status = 'error';
                $msg = $this->upload->display_errors('', '');
            }
        else
            {
                $data = $this->upload->data();
                //$data['file_name']
                $status = "success";
                $msg = "File successfully uploaded";
            }
        echo json_encode(array('status' => $status, 'msg' => $msg));
    }

Error that i am getting in console is:

我在控制台输入的错误是:

{status: "error", msg: "You did not select a file to upload."}

{状态:“错误”,msg:“您没有选择要上传的文件。”}

Can anyone please tell how to upload file

有人能告诉我怎么上传文件吗?

3 个解决方案

#1


2  

Try Using This code for script:

尝试使用以下代码编写脚本:

<script type="text/javascript">
    $(document).ready(function() {
    $("#submit_first_form").click(function(event) {
    event.preventDefault();
    var form_data = new FormData($('#first_form')[0]);

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: form_data,
        processData: false,
        contentType: false,
        success: function(res) {
        if (res)
            {
                console.log(res);
            }
        }
    }); }); });
</script>

#2


0  

<form id="first_form" method="post" enctype="multipart/form-data">

The enctype when file upload.

当文件上传的时候。

#3


0  

-> give id in form tag Submit and add a submit button before form close script to send request $("#save").click(function (event) { event.preventDefault();

->在表单标签提交中提供id,并在表单关闭脚本之前添加提交按钮,以发送请求$(“#save”)。点击(函数(事件){ event.preventDefault();

// Create an FormData object
    var data1 = new FormData($('#fileUploadForm')[0]);
      console.log($('#fileUploadForm'));
$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: data1,
        processData: false,
        contentType: false,
        cache: false,

        success: function (data) {
        data = JSON.parse(data);
        console.log(data);
        if(data.id==1)
        {
          localStorage.setItem("user_profile_pic", data.user_pic);

          alert("updated sucessfully")

        }



        }
    });

#1


2  

Try Using This code for script:

尝试使用以下代码编写脚本:

<script type="text/javascript">
    $(document).ready(function() {
    $("#submit_first_form").click(function(event) {
    event.preventDefault();
    var form_data = new FormData($('#first_form')[0]);

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: form_data,
        processData: false,
        contentType: false,
        success: function(res) {
        if (res)
            {
                console.log(res);
            }
        }
    }); }); });
</script>

#2


0  

<form id="first_form" method="post" enctype="multipart/form-data">

The enctype when file upload.

当文件上传的时候。

#3


0  

-> give id in form tag Submit and add a submit button before form close script to send request $("#save").click(function (event) { event.preventDefault();

->在表单标签提交中提供id,并在表单关闭脚本之前添加提交按钮,以发送请求$(“#save”)。点击(函数(事件){ event.preventDefault();

// Create an FormData object
    var data1 = new FormData($('#fileUploadForm')[0]);
      console.log($('#fileUploadForm'));
$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "<?php echo base_url(); ?>" + "student/add_data",
        data: data1,
        processData: false,
        contentType: false,
        cache: false,

        success: function (data) {
        data = JSON.parse(data);
        console.log(data);
        if(data.id==1)
        {
          localStorage.setItem("user_profile_pic", data.user_pic);

          alert("updated sucessfully")

        }



        }
    });