【问题标题】:how to upload file in codeigniter without submit button?如何在没有提交按钮的情况下在codeigniter中上传文件?
【发布时间】:2013-07-28 01:48:28
【问题描述】:

我有一个使用 codeigniter 上传文件的脚本,但它仍然使用提交按钮。我想上传而不点击提交。这是我的脚本:

controllers/gallery.php

<?php
class Gallery extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
    }

    function index(){
        $this->load->model('MGallery');
        if($this->input->post('upload')){
            $this->MGallery->do_upload();
        }

    $this->load->view('gallery_view');
    }
}
?>

models/mgallery.php

<?php
class MGallery extends CI_Model{

var $gallery_path;

public function __construct()
{
    parent::__construct();
    $this->gallery_path = realpath(APPPATH . '../images');
}

function do_upload(){
   $config = array(
      'allowed_types'=>'jpg|jpeg|gif|png',
      'upload_path' => $this->gallery_path,
      'max_size' => 2000
   );

    $this->load->library('upload',$config);
    $this->upload->do_upload();
    $image_data = $this->upload->data();

    $config = array(
       'source_image'=> $image_data['full_path'],
       'new_image'=>$this->gallery_path . '/thumbs',
       'maintain_ration'=>true,
       'width'=>160,
       'height'=>120
    );

    $this->load->library('image_lib', $config);
    $this->image_lib->resize();
  }
}

*views/gallery_view.php*

<!DOCTYPE HTML>

<html lang="en-US">

    <head>
        <title>Gallery With CI</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="gallery">
        </div>

        <div id="upload">

            <?php echo form_open_multipart('gallery'); ?>
            <?php echo form_upload('userfile');?>

            <?php echo form_submit('upload','Upload'); ?>
            <?php echo form_close(); ?>

        </div>
 </body>

如果我想让它在没有提交按钮的情况下上传,我该怎么办?

【问题讨论】:

    标签: php codeigniter upload submit multipart


    【解决方案1】:

    为了能够上传您的文件,您需要在刚刚浏览文件时触发一些 JavaScript 函数。下面的代码可能会帮助您使用 JQuery AJAX 库来做到这一点。

    $upload_field_info = array('class' => 'file_upload', 'id' => 'file_upload', 'name' => 'file_upload');
    echo form_input($upload_field_info);  
    

    在你的视图中编写一个 javascript 函数:

    $('#file_upload').change(function(){  
    var upload_data = $('#file_upload').val()
    var post_url = "<?php echo base_url();?>index.php/gallery/upload";
    $.ajax({
        type: "POST",
        url: post_url,
        data: upload_data,
        datatype: "json",
        success: function(data) 
        {
            $('#upload_result_div').html("<span class=success>File Uploaded!</span>");
        }
    });
    

    您将需要一个名为“上传”的函数在您的“图库”控制器中!

    【讨论】:

    • 你能给我更多关于每个模型、视图、控制器的详细脚本吗?我已经尝试了上面的解决方案,但是我上传的图像没有存储在目标文件夹中..对不起,我还是新手..
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 2021-12-20
    • 2016-08-29
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多