Rizki Kurniawan
Rizki Kurniawan

Reputation: 5

How i can do download file from database using CodeIgniter based on the file id?

$this->load->helper('download');

//get file info from database
$id = $this->uri->segment(4);
$fileInfo['gambar'] = $this->mod_surat_masuk->download($id);

//download file from directory
$file = 'gambar_product'.$file['gambar'];
force_download($file, NULL);

that my code but didn't work anyway so how can I make download function using Codeigniter based on the file id?

Upvotes: 0

Views: 884

Answers (2)

Pathik Vejani
Pathik Vejani

Reputation: 4491

Try this:

<?php
$this->load->helper('download');
//get file info from database
$id = $this->uri->segment(4);
$fileInfo = $this->mod_surat_masuk->download($id);

$source_file = file_get_contents(base_url() . 'gambar_product/' . $fileInfo['NAME_OF_THE_FILE']);
$file_name = $fileInfo['NAME_OF_THE_FILE'];
ob_clean();
force_download($file_name, $source_file);
?>

Upvotes: 0

Nisha
Nisha

Reputation: 633

CodeIgniter has a nice helper function to download files.

public function download ($file_path = ""){
    // load ci download helder
    $this->load->helper('download');  

    // get download file path and store it in $data array
    $data['download_file'] = $file_path;  

    // load view file    
    $this->load->view("download_view",$data);
    redirect(current_url(), "refresh");                       
}

In view section (download_view.php), just call the download function that's it.

if(! empty($download_file))
{
    $data = file_get_contents(base_url("/path/".$download_file)); 
    // Read the file's contents
    $name = $download_file;
    force_download($name, $data);
}

Upvotes: 1

Related Questions