Ajax 上传代码点火器不起作用


Ajax upload not working codeigniter

我正在使用代码点火器 3.1 .我想使用 ajax 发布上传数据。

Ajax 上传文件不起作用。但是当我发布没有 ajax 的简单表单时,它工作正常。

我不知道为什么,但控制台中没有错误。

.HTML

  <?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
    <input type="file" name="userfile" value="">
    <input type="submit" value="Submit" />
  <?php echo form_close() ?>

JAVASCRIPT

   $('#uploader').submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: window.location.href + '/post',
                type: "POST",
                dataType: 'json',
                data: new FormData(this)
               });
      });

控制器

 public function post() 
    {
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library("upload");
        $file = $this->common->nohtml($this->input->post("userfile"));
        $this->upload->initialize(array( 
               "upload_path" => 'upload',
               "overwrite" => FALSE,
               "max_filename" => 300,
               "encrypt_name" => TRUE
            ));
        $this->upload->do_upload('userfile');
        $data = $this->upload->data();
        $image_file = $data['file_name'];
  }

另一种方法是将 base64 编码的文件传递给 PHP:

  • 使用 $('#userfile').prop('files')[0]#userfile字段中获取所选文件 ;
  • 使用 FileReader.readAsDataURL(( 将该文件的内容转换为 base64 编码的字符串。我们称之为content;这是一个类似的问题,展示了如何做并扩展答案和可能性;
  • 发送传递filenamecontent字符串的 AJAX;
  • 现在在 CI 上,获取 POST 数据;
  • base64_decode(( content ;
  • fwrite(( 使用filename将结果放入文件中。

这样,您也可以避免发布所有表单字段。

试试这个。也使用表单数据发布文件FormData()数据发布数据。若要获取所有表单输入,包括type="file",您需要使用 FormData 对象

$('#post').on('click', function (e) {
    var file_data = $("#userfile").prop("files")[0];      
    var form_data = new FormData();                  
    form_data.append("userfile", file_data)
    $.ajax({
            url: window.location.href+'/post',
            type: 'POST',
            data: form_data,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
   return false;
});

更多...https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

其中一个

问题是文件上传使用的机制与其他表单<input>类型不同。这就是为什么$this->input->post("userfile")没有为你完成工作。其他答案建议使用javascript的FormData,这个也是如此。

.HTML

一个非常简单的表单,用于选择文件并提交它。请注意从简单按钮更改为<input type="submit"... 。这样做使 javascript 更容易使用 FormData 对象。

表单数据文档

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="https://code.jquery.com/jquery-2.2.2.js"></script>
        <title>Upload Test</title>
    </head>
    <body>
        <?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
        <input type="file" name="userfile">
        <p>
            <input type="submit" value="Upload">
        </p>
        <?php echo form_close() ?>
        <div id="message"></div>
        <script>
            $('#uploader').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: window.location.href + '/post',
                    type: "POST",
                    dataType: 'json',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log(data);
                        if (data.result === true) {
                            $("#message").html("<p>File Upload Succeeded</p>");
                        } else {
                            $("#message").html("<p>File Upload Failed!</p>");
                        }
                        $("#message").append(data.message);
                    }
                });
            });
        </script>
    </body>
</html>

JAVASCRIPT

使用FormData捕获字段。请注意,我们处理的不是按钮单击,而是提交事件。

$('#uploader').submit(function (event) {
    event.preventDefault();
    $.ajax({
        url: window.location.href + '/post',
        type: "POST",
        dataType: 'json',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data) {
            //uncomment the next line to log the returned data in the javascript console
            // console.log(data);
            if (data.result === true) {
                $("#message").html("<p>File Upload Succeeded</p>");
            } else {
                $("#message").html("<p>File Upload Failed!</p>");
            }
            $("#message").append(data.message);
        }
    });
});

控制器

我添加了一些将结果"报告"到 ajax 的代码,并将其显示在上传页面上。

class Upload extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(['form', 'url']);
    }
    public function index()
    {
        $this->load->view('upload_v');
    }
    public function post()
    {
        $this->load->library("upload");
        $this->upload->initialize(array(
                "upload_path" => './uploads/',
                'allowed_types' => 'gif|jpg|png|doc|txt',
                "overwrite" => FALSE,
                "max_filename" => 300,
                "encrypt_name" => TRUE,
        ));
        $successful = $this->upload->do_upload('userfile');
        if($successful)
        {
            $data = $this->upload->data();
            $image_file = $data['file_name'];
            $msg = "<p>File: {$image_file}</p>";
            $this->data_models->update($this->data->INFO, array("image" => $image_file));
        } else {
            $msg = $this->upload->display_errors();
        }
        echo json_encode(['result' => $successful, 'message' => $msg]);
    }
}

这将上传您的文件。您的工作可能尚未完成,因为我怀疑您没有将所需的所有文件信息保存到数据库中。那个,我怀疑你会对上传文件的名称感到惊讶。

我建议你研究一下PHP如何处理文件上传,并在SO上检查一些类似的代码点火器相关的文件上传问题。

控制器

public function upload()
{
$this->load->library('upload');
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
{
    if ($_FILES['myfile']['error'] != 4)
    {
         // Image file configurations
        $config['upload_path'] = './upload/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $this->upload->initialize($config);
        $this->upload->do_upload('myfile');
    }
  }
 }

视图

<form id="myform" action="<?php base_url('controller/method'); ?>" method="post">
<input type="file" name="myfile">

("#myform").submit(function(evt){
evt.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
    url: url,
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function (res) {
        console.log(res);
    },
    error: function (error) {
        console.log(error);
    }
}); // End: $.ajax()           
}); // End: submit()

如果有任何疑问,请告诉我

您需要提交表格,而不是点击提交...给表单一个 ID,然后在提交时输入 Ajax

.HTML

<?php $attributes = array('id' => 'post'); ?>
<?php echo form_open_multipart(site_url("upload/post",$attributes), ?>
    <input type="file" id="userfile" name="userfile" value="">
    <button id="post">Submit</button>
  <?php echo form_close() ?>

JAVASCRIPT

$('#post'(.on('submit', function (( {

    var formData = new FormData();
    formData.append("userfile",$("#userfile")[0].files[0]);
    $.ajax({
            url: window.location.href+'/post',
            type: "POST",
            data: formData
        });

控制器

public function post() 
    {
        $this->load->library("upload");
        $file = $this->common->nohtml($this->input->post("userfile"));
    $this->upload->initialize(array( 
           "upload_path" => 'upload',
           "overwrite" => FALSE,
           "max_filename" => 300,
           "encrypt_name" => TRUE,
        ));
    $data = $this->upload->data();
    $image_file = $data['file_name'];
    $this->data_models->update($this->data->INFO, array(
      "image" => $image_file
        )
      );

}