2014-11-11 2 views
0

Я хочу принудительно загрузить после отправки (файл .docx, сгенерированный с помощью PhpWord), и перенаправить на другую страницу за одно и то же время.Codeigniter - перенаправить и загрузить файл

здесь код генерации файла DOCX:

$objWriter->save($filename); 
header('Content-Description: File Transfer'); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.$filename); 
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Pragma: public'); 
header('Content-Length: ' . filesize($filename)); 
header('Location: http://localhost/contracto_0.4/index.php/contrac) 
readfile($filename); 
unlink($filename); // deletes the temporary file 

После этого, я пытаюсь загрузить вид, и я это сообщение от PHP:

Cannot modify header information - headers already sent by (output started at C:\wamp\www\contracto_0.5\system\core\Exceptions.php:185) 

ответ

0

Вы можете использовать download_helper:

if (! function_exists('force_download')) 
{ 
function force_download($filename = '', $data = '') 
{ 
    if ($filename == '' OR $data == '') 
    { 
    return FALSE; 
    } 

    // Try to determine if the filename includes a file extension. 
    // We need it in order to set the MIME type 
    if (FALSE === strpos($filename, '.')) 
    { 
    return FALSE; 
    } 

    // Grab the file extension 
    $x = explode('.', $filename); 
    $extension = end($x); 

    // Load the mime types 
    @include(APPPATH.'config/mimes'.EXT); 

    // Set a default mime if we can't find it 
    if (! isset($mimes[$extension])) 
    { 
    $mime = 'application/octet-stream'; 
    } 
    else 
    { 
    $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension]; 
    } 

    // Generate the server headers 
    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) 
    { 
    header('Content-Type: "'.$mime.'"'); 
    header('Content-Disposition: attachment; filename="'.$filename.'"'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header("Content-Transfer-Encoding: binary"); 
    header('Pragma: public'); 
    header("Content-Length: ".strlen($data)); 
    } 
    else 
    { 
    header('Content-Type: "'.$mime.'"'); 
    header('Content-Disposition: attachment; filename="'.$filename.'"'); 
    header("Content-Transfer-Encoding: binary"); 
    header('Expires: 0'); 
    header('Pragma: no-cache'); 
    header("Content-Length: ".strlen($data)); 
    } 

    exit($data); 
} 
} 

и в контроллере:

function donwload(){ 
$this->load->helper('download'); 
$data = file_get_contents('path/file.docx'); 
force_download('file.docx', $data); 
} 

выше кода, доступного в ellislab.com

+0

это работает для меня! – deadman

0

использования попробовать

redirect($filename); 

если не работает

в файле index.php codeignaiter добавить следующее найти в корневой папке добавить я решить Невозможно изменить заголовок информация - заголовки уже отправлены по ошибке и перенаправлены

ob_start(); 
0

Вероятно, его из-за этих двух строк кода у вас есть, пожалуйста, изменить эти две строки

header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename='.$filename); 

К

header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="' . $filename . '"'); 

ИЛИ

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
header('Content-Disposition: attachment; filename="' . $filename . '"'); 

Возможно, у меня нет объяснять вам по строкам, потому что это очень легко понять. Пожалуйста, обратитесь к моему старому коду ниже в качестве руководства .. и на самом деле он все еще работает на моем сайте. Не стесняйтесь тестировать и изменять его.

$error = '<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>'; 

if(isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) 
{ 
    $filename = $_GET['file']; 
} 
else 
{ 
    $filename = null; 
} 

if($filename != null) 
{ 
    $path = '../files/' . $filename; 
    if (file_exists($path) && is_readable($path)) 
    { 
     header('Pragma: public'); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
     header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
     header('Content-Disposition: attachment; filename="' . $filename . '"'); 
     header('Content-Length: ' . filesize($path)); 
     header('Content-Transfer-Encoding: binary'); 

     $file = @fopen($path, 'rb'); 
     if($file) 
     { 
      fpassthru($file); 
      exit; 
     } 
     else 
     { 
      echo $error; 
     } 
    } 
    else 
    { 
     echo $error; 
    } 
} 
else 
{ 
    echo $error; 
} 
Смежные вопросы