在Codeigniter中使用Ajax上传文件 - javascript

我正在尝试上传包含其他数据的文件。问题是我收到错误消息,您未选择要上传的文件。我不明白我做错了什么。如果有人能指出我做错了什么,我将感到非常高兴。谢谢

html文件

 <div class="modal-body">
          <form id="add_message" enctype="multipart/form-data"  method="post" action="<?php echo base_url() ?>apps/messages/composeMessage">

            <div class="form-group">
              <select id="messageTo" class="form-control" data-plugin="select2" multiple="multiple" data-placeholder="To:" name="messageTo">
              </select>
            </div>

            <div class="form-group">
              <input class="form-control" placeholder="Subject" id="messageSubject" name="messageSubject"></input>
            </div>

            <div class="form-group">
              <textarea  data-provide="markdown" data-iconlibrary="fa" rows="10" id="messageBody" name="messageBody"></textarea>
            </div>

            <input type="hidden" name="fname" value="" id="formName" ></input>

            <div class="left">

                <!-- <span class="btn green fileinput-button"> -->

                    <input id="message_attachement" type="file" name="file_attac" size="20" >
                <!-- </span> -->
            </div>
            <!-- <button class="btn btn-primary"  type="submit" value="submit">Send</button> -->
          </form>
        </div>
        <div class="modal-footer text-left">
          <button class="btn btn-primary" data-dismiss="modal"  id="addformButton">Send</button>
          <button class="btn btn-primary" data-dismiss="modal"  id="saveformButton">Save</button>
          <a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Cancel</a>
        </div>

JS

$("#addformButton").on('click' , function(){
    debugger;       
        $.ajax({
            type: "POST", 
            url: base_url + "apps/messages/composeMessage",
            async: false,
             mimeType: "multipart/form-data",
            dataType:JSON, 
            data:{
                'reciever': $('#messageTo').val() , 
                'subject': $('#messageSubject').val(),
                'text': $('#messageBody').val(),
                'type': 'active',
                'msgId': $('#formName').val(),
                'attachment' : $('#message_attachement').val()
            },
            success: function(response){
            },
            error: function(response){
            }
        });
    });

控制者

 $this->load->helper('file_upload');
         $filename = $this->input->post('attachment');
          $path = 'uploads/attachments/';
          $allowed_types = 'erb|php|txt';
          $redirect = '';
          // error_log("outside");
          if (!empty($this->input->post('attachment'))) {
              // error_log("inside");
              // error_log ("Parameters: " . $path." Types: ". $allowed_types." name: ". $filename." redirect: ". $redirect);
              $parameters['profile_pic'] = file_upload($path, $allowed_types, $filename, $redirect);
              // error_log("The path is ");
              // error_log($parameters['profile_pic']);
              if ($this->session->set_userdata("img_errors")) {
                // error_log("error");
                return false;
              }
          }

文件上传功能

  function file_upload($upload_path , $allowed_types , $filename , $redirect)
  {
      $ci = & get_instance();

      $config['upload_path'] = $upload_path;
      $config['allowed_types'] = $allowed_types;
      // $config['max_size'] = 1024;//1mb
      // $config['max_width'] = 1024;
      // $config['max_height'] = 1024;

      $ci->load->library('upload', $config);
      $data = NULL;
      if (!$ci->upload->do_upload($filename)) {
        error_log("within the file");
//          $error = array('error' => $ci->upload->display_errors());
        error_log($ci->upload->display_errors());
          $ci->session->set_userdata('img_errors', $ci->upload->display_errors());
          //error_log(print_r($ci->upload->display_errors(),true));
          // redirect(base_url() . $redirect);
      } else {
        error_log("uploading");
          $data = array('upload_data' => $ci->upload->data());
          // do_resize($config['upload_path'] , $data['upload_data']['file_name']);
      }

      return $config['upload_path'] . $data['upload_data']['file_name'];
  }

参考方案

这是我在最近的项目中使用的工作代码,该代码可以自我解释,但是随时可以提出任何问题。

HTML:

                <form action="http://localhost/index.php/upload_file" method="post" style="display:none;" id="file_upload_form" enctype="multipart/form-data">
                    <input type="file" id="dialog_triggerer" name="uploaded_file">
                </form>

                <button class="btn btn-default btn-fab-sm" id="file_attach">
                    <span class="mdi-file-attachment"></span>
                </button>

JS:

在某些操作上触发此代码:

            var form = $('form')[0]; // standard javascript object here
            var formData = new FormData(form);

            if($("#dialog_triggerer").val()!=""){

                $.ajax( {
                  url: FRONTEND_URL + '/upload_file',
                  type: 'POST',
                  data: formData,
                  processData: false,
                  contentType: false,
                  async: false
                } ).done(function(data){
                    file_data = JSON.parse(data);
                    new_post.file_data = file_data;
                }); 

            }

upload_file ctrl:

<?php

class Upload_file extends CI_Controller{
    public function __construct(){
        parent::__construct();
    }

    public function index(){

        $valid_file=true;
        $message;


        //if they DID upload a file...
        if($_FILES['uploaded_file']['name'])
        {
            //if no errors...
            if(!$_FILES['uploaded_file']['error'])
            {
                //now is the time to modify the future file name and validate the file
                $new_file_name = strtolower($_FILES['uploaded_file']['name']); //rename file
                if($_FILES['uploaded_file']['size'] > (20024000)) //can't be larger than 20 MB
                {
                    $valid_file = false;
                    $message = 'Oops!  Your file\'s size is to large.';
                }

                //if the file has passed the test
                if($valid_file)
                {
                    $file_path = 'themes/uploads/'.$new_file_name;
                    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], FCPATH . $file_path);
                    $message = 'Congratulations!  Your file was accepted.';
                }
            }
            //if there is an error...
            else
            {
                //set that to be the returned message
                $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['uploaded_file']['error'];
            }
        }
        $save_path = base_url().$file_path;

        $name = $_FILES['uploaded_file']['name'];
        $size = $_FILES['uploaded_file']['size'];
        $type = $_FILES['uploaded_file']['type'];


        $data = array(
            "message" => $message,
            "save" => $save_path,
            "name" => $name,
            "size" => $size,
            "type" => $type
        );

        $this->load->view('upload_file/upload_file.php', $data);


    }
}

upload_file.php视图:

<?php

$res = array(
    "msg" => $message,
    "path" => $save,
    "name" => $name,
    "size" => $size,
    "type" => $type
);

echo json_encode($res);



?>

打印二维阵列 - javascript

我正在尝试打印子元素。在this example之后。怎么做?。$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'), "JOCKEY"=>a…

保留文本区域的数据或值,然后选择输入 - javascript

通过$ _POST提交表单时,输入文件值仍然保留。像这样: if($_POST){ $error = false; if(!$post['price']){ $error = true; $error_note['price'] = "*Should not be empty"; } if($err…

变更事件时道具无法正常工作 - javascript

我有一些代码,当用户从下拉列表中选择一个项目时,这会触发一个change事件,然后调用php页面进行处理。首次加载页面时,我选择一个项目,并在触发change事件时,这应更改所选select输入的占位符并禁用相同的输入:“#box_ffrtv”。但是,发生的事情是更改仅在我在下拉菜单中进行了第二选择之后才发生,然后更改了占位符并禁用了输入。我对jquery还…

将简单的javascript代码转换为c# - javascript

昨天我在这里问了一个问题。使用javascript和html解决方案很简单前一阵子我打算什么是操纵html来执行javascript中的任务但是我改变了主意,将javascript代码重写为c#这是输入<Abstract> <Heading>Abstract</Heading> <Para TextBreak=�…

包含“。”的onClick函数参数 - javascript

我正在尝试创建一个表,该表包含该表的“更改密码”列中各项的onClick函数,以便我的系统管理员可以更改每个人的密码。每个onClick都会调用函数“ ChangePassOpen”,该函数将打开一个带有新密码输入框和另一个按钮的模式,以实际调用该函数来更改密码。为了使我的程序能够识别管理员正在更改的帐户,我需要将用户名作为参数传递,但是我的用户名包含“。”…