Ajax上传不工作codeigniter [英] Ajax upload not working codeigniter

查看:103
本文介绍了Ajax上传不工作codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用codeigniter 3.1。我想使用ajax发布上传数据。



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



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



HTML

 <?php echo form_open_multipart(site_url post),['id'=>'uploader'])> 
< input type =filename =userfilevalue =>
< input type =submitvalue =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)
});
});


CONTROLLERS

  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'];

}


解决方案

问题是文件上传使用与其他形式< input> 类型不同的机制。这就是为什么 $ this-> input-> post(userfile)没有得到你的工作。其他答案建议使用javascript的 FormData ,这也是一样。



HTML / p>

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



FormData文档

 <!DOCTYPE html> 
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8/>
< script src =https://code.jquery.com/jquery-2.2.2.js>< / script>
< title>上传测试< / title>
< / head>
< body>

<?= form_open_multipart(upload / post,['id'=>'uploader']); >
< input type =filename =userfile>
< p>
< input type =submitvalue =上传>
< / 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){
$( ).html(< p> File Upload Succeeded< / p>);
} else {
$(#message)。html ; / p>);
}
$(#message)append(data.message);
}
});
< / script>
< / body>
< / html>



JAVASCRIPT



使用 FormData 捕获字段。
注意,我们不处理按钮点击,而是处理submit事件。

  $('#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 ){
//取消注释在javascript控制台中记录返回数据的下一行
// console.log(data);
if(data.result === true){
$(#message)。html(< p> File Upload Succeeded< / p>);
} else {
$(#message)。html < p>文件上传失败!< / p>);
}
$(#message)append(data.message);
}
} );
});

CONTROLLER



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

  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>文件:{$ 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]);
}

}

这将上传您的文件。你的工作可能没有完成,因为我怀疑你没有保存你需要的所有文件信息db。这,我怀疑你会对上传的文件的名称感到惊讶。



我建议你学习PHP 处理文件上传,并在此处查看与文件上传相关的一些类似的代码信息相关问题。


I am using codeigniter 3.1 . I want to post upload data using ajax.

Ajax upload file not working. But when i post the simple form without ajax, it working fine.

I don't know why but no error in console.

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)
               });
      });

CONTROLLERS

 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'];

  }

解决方案

One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.

HTML

A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.

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

Use FormData to capture the fields. Note that instead of handling the button click we handle the submit event.

$('#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);
        }
    });
});

CONTROLLER

I've added some code that "reports" results to ajax and will display it on the upload page.

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]);
    }

}

This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.

I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.

这篇关于Ajax上传不工作codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆