简体   繁体   English

使用Jquery Ajax的代码点火器文件上传类

[英]Code Igniter File Uploading Class with Jquery Ajax

So all I am trying to accomplish is simply upload a file with codeigniter using the File Uploading Class 所以我要做的就是简单地使用File Uploading类使用codeigniter上载文件

For my controller I have the following code: 对于我的控制器,我有以下代码:

function do_upload()
{
    $config['upload_path'] = './assets/productImages/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';

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

    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());

        var_dump($error);
    }
    else
    {
        $data = array('upload_data' => $this->upload->data());
    }
}

And then my form is as follows: 然后我的形式如下:

$data['productImage'] = array(
   "name" => "userfile",
   "id" => "product_image",
);

 // displays out as: 
 <input type="file" name="userfile" value="" id="product_image">

My javascript is as follows which uses an onchange action to trigger the upload process. 我的JavaScript如下,它使用onchange动作触发上传过程。

$("document").ready(function(){
            $("#product_image").change(function() {
                var path = $(this).val();
                var dataString = 'userfile=' + path;
                //alert(dataString); return false;
                $.ajax({
                    type: "POST",
                    url: "/account/do_upload/",
                    data: dataString,
                    success: function(data) {
                        alert(data);
                    }
                });
                return false;
            });
        });

When I run this code, I receive this message in the javascript alert 运行此代码时,我在javascript警报中收到此消息

You did not select a file to upload.

What do I need to add to make this work? 我需要添加什么才能使它正常工作? I'm guessing it has something to do with processing the upload through the javascript ajax. 我猜想这与通过javascript ajax处理上传有关。

* UPDATE DUE TO COMMENTS * *由于评论而更新*

My form tag is as follows: 我的表单标签如下:

$data['newPostForm'] = array('id' => 'newPostForm', 'type' => 'multipart');

// And echoes out as :
 <form action="http://myurl.com/index.php/account/submitPost" method="post" accept-charset="utf-8" id="newPostForm" type="multipart">

Your codeigniter code looks fine. 您的codeigniter代码看起来不错。
The problem is that you can't upload files directly through Ajax. 问题是您不能直接通过Ajax上传文件。 You need to do it though an iframe. 您需要通过iframe进行操作。
This plugin here works a treat. 这个插件在这里工作。
Or if you only need it to work in html 5 then this should do the treat http://www.devbridge.com/projects/html5-ajax-file-upload/ 或者,如果您只需要它在html 5中工作,则应该使用http://www.devbridge.com/projects/html5-ajax-file-upload/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM