更改下载文件名codeigniter

时间:2017-02-14 08:03:53

标签: codeigniter

强行下载前转换文件名。

我试图能够在下载之前将存储的文件名的文件名转换为orignal文件名

因此,当用户点击要下载的文件而不是显示

post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php

如下图所示

它只会将下载的文件重命名为

config.php

enter image description here

  

询问如何在点击图片时更改下载的文件名。

public function downloads($id) {
    $this->db->where('attachment_id', $id);
    $query = $this->db->get('attachments');

    if ($query->num_rows() == 0) {
       return false;
    }

    $path = '';
    $file = '';

    foreach ($query->result_array() as $result) {

        $path .= FCPATH . 'uploads/'; 

        // This gives the stored file name
        // This is folder 201702
        // Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php

        $stored_file_name .= $result['attachment_name']; 

        // Out puts just example "config.php"
        $original .= $result['file_name']; 

    }

    force_download($path . $stored_file_name, NULL);
}

3 个答案:

答案 0 :(得分:2)

那怎么样 (imho你的foreach循环没有任何意义)

public function downloads($id) {
    $this->db->where('attachment_id', $id);
    $query = $this->db->get('attachments');

    if ($query->num_rows() == 0) {
       return false;
    }

    $path = '';
    $file = '';

    foreach ($query->result_array() as $result) {

        $path .= FCPATH . 'uploads/'; 

        // This gives the stored file name
        // This is folder 201702
        // Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php

        $stored_file_name .= $result['attachment_name']; 

        // Out puts just example "config.php"
        $original .= $result['file_name']; 

    }

    force_download("your_filename.txt",file_get_contents($path . $stored_file_name));
}

答案 1 :(得分:0)

很简单!

force_download(
    $filenameWithFileExtension, 
    file_get_contents($fileToDownload), 
    mime_content_type($fileToDownload)
);

答案 2 :(得分:0)

在这种情况下,请使用force_download()这样的内容-

$file_name = "using md5 to convert it on normal text and stroe variable";
$file_path = "It's your file path, where have file in your drive"
$file_path = 'uploads/'.$path; 
force_download($file_name, file_get_contents($file_path));

这很简单而且工作正常。只需要将文件路径和文件名存储在2个不同的变量中,然后将它们传递给force_download()。 希望它能工作。 祝你好运。