Codeigniter Ajax上传图片 [英] Codeigniter Ajax Upload image

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

问题描述

我目前正在使用CodeIgniter为我的学校项目开发一些表格.

我的想法是我有一个带有图片上传功能的表单.我正在尝试使用Ajax动态地执行此操作,但它似乎根本不起作用.我用php尝试了非动态版本,并且运行良好,图像在我的文件夹中,没有问题.

我尝试了5个或6个插件,但都没有结果,这肯定是我的错,但我不知道自己在哪里犯了错误.

< ---控制器--->

if($result = $this->images_model->add_bdd())
{   
    $data['uploaded'] = $result;
    $data['message_upload'] = 'Image uploader avec succès.';                            
    $this->template->set_title('Upload successful');
    $this->template->view('add_places',$data);
}
else
{   
    $this->template->set_title('Upload failed');
    $this->template->view('add_places');
}

<-模型->

function add_bdd()
{
    $config = array(
                'allowed_types' => 'jpg|jpeg|tiff',
                'upload_path' => $this->gallery_path,
                'max_size' => 2000,
                'remove_spaces' => TRUE,
                'overwrite' => FALSE
            );

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

        $data_img = $this->upload->data();
        $exif = $this->exif_extractor->coords($data_img['full_path']);
        $data = array(
                'titre' => 'titlecontent',
                'url' => base_url('images/'.$data_img['file_name']),
                'url_min' => base_url('images/'.$data_img['raw_name'].'_min'.$data_img['file_ext']),
                'alt' => 'cover_contentName',
                'id_users' => $this->session->userdata('id'),
                'date_upload' => date('Y-m-d H:m'),
                'date_modified' => date('Y-m-d H:m'),
                'lat' => $exif[0],
                'long' => $exif[1],
                );
        $this->db->insert('pictures',$data);
        return $exif;
    }
    else
    {
        return false;
    }
}

<-查看->

<form action="http://localhost:8888/project/images/add" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile" value="Image de couverture"  />
<button name="upload" type="button" id="upload">Upload</button>
<input type="submit" name="submit" value="Publish Place"  />
</form>

任何人都可以给我一个jQuery插件来动态上传图像并将包含我要返回的路径和其他数据的图像发送回脚本吗?

我不能像我为jQuery创建的所有代码一样粘贴,但是我确实需要帮助.我已经呆了2天了!

感谢您的帮助.

解决方案

感谢您的帮助,我更改了脚本的动态,因此,现在,它可以完美地满足我的工作.

有用于我的上传系统的脚本:

<-查看(upload_img)->

<div id="container">
<div id="filelist"></div>
<a href="http://localhost:8888/myproject/#" id="userfile" name="userfile">[Select files]      </a>    
<a href="http://localhost:8888/myproject/images/index#" id="uploadfiles">[Upload files]</a
</div>

<-控制器->

function index(){
    if($this->_access())
    {
        $this->template->add_include('js/jquery.js')
                       ->add_include('js/browserplus.js')
                       ->add_include('js/plugins/plupload/plupload.full.js')
                       ->add_include('js/imgfunc.js');
        $this->template->view('upload_img');
    }
    else
    {
        redirect(site_url());
    }
}

function upload_image_spot()
{
    if($query = $this->images_model->upload_image_spot())
    {
        echo json_encode($query);
    }
    else
    {
        echo $this->upload->display_errors('', '');
    }
}

<-模型->

   function upload_image_spot()
{
    $config['upload_path'] = realpath(APPPATH. '../images/spots');
    $config['allowed_types'] = 'jpg|jpeg|tiff|png';
    $config['max_size'] = 3062;
    $config['encrypt_name'] = TRUE;
    $this->load->library('upload', $config);
    if($this->upload->do_upload('file')) 
    // file means the file send to the website for upload, this is the name of field for Plupload script
    {
    $data_img = $this->upload->data();
    $copies = array(
            array('dir' => 'images/spots/large/', 'x' => 1000, 'y' => 600),
            array('dir' => 'images/spots/thumb/', 'x' => 100, 'y' => 60)
    );

    $this->copies($data_img,$copies);

    return 'whatever'; // Not real data, I don't wanna post them here
    }
}

<-JS脚本->

首先包括:

-jQuery

-browserPlus

-Plupload

(加载脚本)

现在将此脚本添加到一个空文件中:

var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'userfile',
    container : 'container',
    max_file_size : '3mb',
    url : 'yourUploadFunctionCI',
    flash_swf_url : 'plugins/plupload/js/plupload.flash.swf',
    silverlight_xap_url : 'plugins/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,jpeg,JPG,JPEG,tiff,png"},
    ]
});

uploader.bind('Init', function(up, params) {
});

$('#uploadfiles').click(function(e) {
    uploader.start();
    e.preventDefault();
});

uploader.init();

uploader.bind('FilesAdded', function(up, files) {
    $.each(files, function(i, file) {
        $('#filelist').html("");
        $('#filelist').append(
            '<div id="' + file.id + '">' +
            file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
        '</div>');
    });

    up.refresh();
});

uploader.bind('UploadProgress', function(up, file) {
    $('#' + file.id + " b").html(file.percent + "%");
});

uploader.bind('Error', function(up, err, msg,file) {
    $('#filelist').append("<div>Error: " + err.code +
        ", Message: " + err.message +
        (err.file ? ", File: " + err.file.name : "") +
        "</div>"
    );
    console.log(msg,up,err);
    up.refresh();
});

uploader.bind('FileUploaded', function(up, file,response) {
    $('#' + file.id + " b").html("100%");
    var data = jQuery.parseJSON(msg.response);
    console.log(data);
});

做您自己的自定义,仅此而已,不需要额外的脚本,如您可以在网站上看到的那样,例如将所有脚本从php文件复制/粘贴到控制器,只需在do_upload内添加文件",一切就可以正常工作!

祝您有美好的一天,希望对您有所帮助.

西蒙(Simon)

I'm currently developping some forms for my school project with CodeIgniter.

The idea is that I have a form with image upload. I'm trying to do it dynamically with Ajax but it seems not working at all. I tried the non-dynamic version with php and It works perfectly, my images are in my folder and I have no problem with it.

I tried like 5 or 6 plug-ins with no results, it is certainly my fault but I don't know where I did a mistakes.

<---Controller--->

if($result = $this->images_model->add_bdd())
{   
    $data['uploaded'] = $result;
    $data['message_upload'] = 'Image uploader avec succès.';                            
    $this->template->set_title('Upload successful');
    $this->template->view('add_places',$data);
}
else
{   
    $this->template->set_title('Upload failed');
    $this->template->view('add_places');
}

<--Model-->

function add_bdd()
{
    $config = array(
                'allowed_types' => 'jpg|jpeg|tiff',
                'upload_path' => $this->gallery_path,
                'max_size' => 2000,
                'remove_spaces' => TRUE,
                'overwrite' => FALSE
            );

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

        $data_img = $this->upload->data();
        $exif = $this->exif_extractor->coords($data_img['full_path']);
        $data = array(
                'titre' => 'titlecontent',
                'url' => base_url('images/'.$data_img['file_name']),
                'url_min' => base_url('images/'.$data_img['raw_name'].'_min'.$data_img['file_ext']),
                'alt' => 'cover_contentName',
                'id_users' => $this->session->userdata('id'),
                'date_upload' => date('Y-m-d H:m'),
                'date_modified' => date('Y-m-d H:m'),
                'lat' => $exif[0],
                'long' => $exif[1],
                );
        $this->db->insert('pictures',$data);
        return $exif;
    }
    else
    {
        return false;
    }
}

<--View-->

<form action="http://localhost:8888/project/images/add" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile" value="Image de couverture"  />
<button name="upload" type="button" id="upload">Upload</button>
<input type="submit" name="submit" value="Publish Place"  />
</form>

Can anyone give me a jQuery plugin to upload images dynamically and send back to the script my images with the path and others data that I want to return ?

I can't paste like all the code I made for jQuery, but I really need help about it. It's been 2 days that I'm on it!

Thanks for your help.

解决方案

Thanks for you help, I change my dynamic about the script so now, it works perfectly with what I have to do.

There is the script for my upload system :

<-- VIEW (upload_img)-->

<div id="container">
<div id="filelist"></div>
<a href="http://localhost:8888/myproject/#" id="userfile" name="userfile">[Select files]      </a>    
<a href="http://localhost:8888/myproject/images/index#" id="uploadfiles">[Upload files]</a
</div>

<-- CONTROLLER -->

function index(){
    if($this->_access())
    {
        $this->template->add_include('js/jquery.js')
                       ->add_include('js/browserplus.js')
                       ->add_include('js/plugins/plupload/plupload.full.js')
                       ->add_include('js/imgfunc.js');
        $this->template->view('upload_img');
    }
    else
    {
        redirect(site_url());
    }
}

function upload_image_spot()
{
    if($query = $this->images_model->upload_image_spot())
    {
        echo json_encode($query);
    }
    else
    {
        echo $this->upload->display_errors('', '');
    }
}

<-- MODEL -->

   function upload_image_spot()
{
    $config['upload_path'] = realpath(APPPATH. '../images/spots');
    $config['allowed_types'] = 'jpg|jpeg|tiff|png';
    $config['max_size'] = 3062;
    $config['encrypt_name'] = TRUE;
    $this->load->library('upload', $config);
    if($this->upload->do_upload('file')) 
    // file means the file send to the website for upload, this is the name of field for Plupload script
    {
    $data_img = $this->upload->data();
    $copies = array(
            array('dir' => 'images/spots/large/', 'x' => 1000, 'y' => 600),
            array('dir' => 'images/spots/thumb/', 'x' => 100, 'y' => 60)
    );

    $this->copies($data_img,$copies);

    return 'whatever'; // Not real data, I don't wanna post them here
    }
}

<-- JS-SCRIPTS -->

First of all include :

-jQuery

-browserPlus

-Plupload

(Plupload Script)

Now add this script in an empty file:

var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'userfile',
    container : 'container',
    max_file_size : '3mb',
    url : 'yourUploadFunctionCI',
    flash_swf_url : 'plugins/plupload/js/plupload.flash.swf',
    silverlight_xap_url : 'plugins/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,jpeg,JPG,JPEG,tiff,png"},
    ]
});

uploader.bind('Init', function(up, params) {
});

$('#uploadfiles').click(function(e) {
    uploader.start();
    e.preventDefault();
});

uploader.init();

uploader.bind('FilesAdded', function(up, files) {
    $.each(files, function(i, file) {
        $('#filelist').html("");
        $('#filelist').append(
            '<div id="' + file.id + '">' +
            file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
        '</div>');
    });

    up.refresh();
});

uploader.bind('UploadProgress', function(up, file) {
    $('#' + file.id + " b").html(file.percent + "%");
});

uploader.bind('Error', function(up, err, msg,file) {
    $('#filelist').append("<div>Error: " + err.code +
        ", Message: " + err.message +
        (err.file ? ", File: " + err.file.name : "") +
        "</div>"
    );
    console.log(msg,up,err);
    up.refresh();
});

uploader.bind('FileUploaded', function(up, file,response) {
    $('#' + file.id + " b").html("100%");
    var data = jQuery.parseJSON(msg.response);
    console.log(data);
});

Do your own customization and that's it, no need extra script like you can see on website like copy/paste all script from a php file to a controller, just add 'file' inside do_upload and everything's gonna work fine !

Have a nice day guys, hope it's help.

Simon

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

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