【问题标题】:Upload file to database using codeigniter使用 codeigniter 将文件上传到数据库
【发布时间】:2012-06-09 11:19:10
【问题描述】:

我需要使用 codeigniter 在 mysql 数据库中上传文件。 我的看法是:

<?php echo form_open_multipart('home/addpagina2'); ?>
<label for="titolo">Titolo:</label>
<input type="text" size="20" id="titolo" name="titolo"/>
<br/>
<label for="testo">Testo</label><br/>
<textarea name="testo" cols="50" rows="10"></textarea>
<br/>
<label for="file">File:</label>
<input type="file" name="file" />
<br />
<input type="submit" value="Aggiungi"/>
</form>

控制器是:

function addpagina2(){
    $this->form_validation->set_rules('titolo', 'Titolo', 'trim');
    $this->form_validation->set_rules('testo', 'Testo', 'trim');

    if($_FILES["file"]["size"] > 0){
        $tmpName = $_FILES["file"]['tmp_name'];         
        $fp = fopen($tmpName, 'r');
        $file = fread($fp, filesize($tmpName));
        $file = addslashes($file);
        fclose($fp);
    }

    $pagina = array();
    $pagina['titolo'] = $this->input->post('titolo');
    $pagina['testo'] = $this->input->post('testo');
    $pagina['file'] = $file;

    $this->db->insert('pagine', $pagina);
    redirect('home/pagine');
}

当我想显示文件时,我称之为视图:

<?php
header("Content-type: ".$file['type']);
echo $file;
?>

由该控制器调用:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class File extends CI_Controller {

function __construct(){
    parent::__construct();
}

public function index(){

}

function id($id){
    $immagine = $this->db->get_where('pagine', array('id' => $id));
    $data['file'] = $immagine->row()->file;
    $this->load->view('file', $data);
}

}

问题是我在浏览器中调用视图时出错,您可以在此处看到:http://mattialori.net/amv/index.php/file/id/2 如果我使用 phpmyadmin 在数据库上上传文件,它可以工作。

我该怎么办?

【问题讨论】:

    标签: codeigniter file-upload


    【解决方案1】:

    为什么不直接将文件名保存到数据库中? 然后您可以将 img 上传到特定文件夹中,在您的视图中,您可以设置文件夹的完整路径并在末尾附加文件名。

    编辑: 你可以这样使用 File Upload 类:

    //Check if the file exists in the form
    if($_FILES['file']['name']!=""){
    
    //load library
    $this->load->library('upload');
    
    //Set the config
    $config['upload_path'] = './uploads/'; //Use relative or absolute path
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = '100';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';
    $config['overwrite'] = FALSE; //If the file exists it will be saved with a progressive number appended
    
    //Initialize
    $this->upload->initialize($config);
    
    //Upload file
    if( ! $this->upload->do_upload("file")){
    
        //echo the errors
        echo $this->upload->display_errors();
    }
    
    
    //If the upload success
    $file_name = $this->upload->file_name;
    
    //Save the file name into the db
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2013-06-13
      • 2013-07-27
      • 1970-01-01
      • 2020-11-09
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多