【问题标题】:Ajax upload not working codeigniterAjax上传不起作用codeigniter
【发布时间】:2017-03-07 10:13:50
【问题描述】:

我正在使用 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'];

  }

【问题讨论】:

  • 您没有将文件传递给上传类,即$file。初始化后你应该有类似if ( ! $this-&gt;upload-&gt;do_upload('userfile')){/*code*/} 的东西。查看上传here的基本示例。
  • 我已经尝试过了,但是没有用。
  • 错误是什么? var_dump('$this-&gt;input-&gt;post('userfile');exit; 检查 PHP 是否正在获取这些数据。
  • 未发现错误。我有更多输入,一切正常,但文件上传不起作用。
  • 您需要选择是使用 AJAX 还是默认表单发布。这样 PHP 在 JS 完成它的工作之前重定向页面。如果你想使用AJAX,你需要结合一些JS库来上传。

标签: javascript php jquery ajax codeigniter


【解决方案1】:

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

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

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

【讨论】:

  • 到底发生了什么?
  • 收到错误upload:24 Uncaught TypeError: Cannot read property '0' of undefined(…)
  • 我认为这取决于我,抱歉,刚刚编辑了答案。您能否尝试将$('#userfile').attr('files')[0]; 替换为$('#userfile').prop('files')[0];
  • 还是不行。收到错误Uncaught TypeError: Illegal invocation(…)
  • @Mehur 你能把你的函数,我的意思是你代码的 JS 部分放到 jsfiddle 或者我们可以更清楚地看到“一切”的地方吗?
【解决方案2】:

试试这个.. 也使用FormData() 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

【讨论】:

  • 好的,但我不想通过 ajax 发送这种形式的更多输入。有什么方法可以只发送文件数据?
  • 不工作。获取Uncaught ReferenceError: formData is not defined(…)
【解决方案3】:

其中一个问题是文件上传使用的机制不同于其他形式的&lt;input&gt; 类型。这就是$this-&gt;input-&gt;post("userfile") 没有为您完成工作的原因。其他答案建议使用 javascript 的FormData,这个也是。

HTML

一个非常简单的表单,用于选择文件并提交它。注意从简单按钮到&lt;input type="submit"... 的变化。这样做可以让 javascript 更容易使用 FormData 对象。

FormData documentation

<!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 handles file uploads 如何在 SO 上查看有关文件上传的一些类似 codeigniter 相关问题。

【讨论】:

  • 忘记在答案中提及这一点,但我不得不将上传目录名称从 upload 更改为 uploads。也许你错过了?除了 data_models-&gt;update() 这是一个模型之外,我没有为我工作的答案代码。当您说“不工作”时。你到底是什么意思?
  • 感谢现在工作。问题出在我的 php 中,但我已修复 :)
  • 一切正常,但成功功能不起作用。 success: function (data) { console.log(data); } 未显示。
  • 但是文件上传OK了吗?
  • 是的,一切正常,但成功功能不起作用。
【解决方案4】:

控制器

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()

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

【讨论】:

【解决方案5】:

你需要提交表单而不是点击提交...给表单一个 id 然后提交 put 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
        )
      );

}

【讨论】:

  • 不工作。获取`upload:24 Uncaught TypeError: Cannot read property '0' of undefined(...)1
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 2013-03-17
  • 2013-12-09
  • 2017-02-05
  • 2018-02-19
相关资源
最近更新 更多