2017-04-12 71 views
0

我有一個Symfony控制器來上傳.docx文件和另一個下載它。如何從Symfony3下載DOCX文檔?

我的symfony控制器下載的文件看起來像這樣:

public function getDocumentationAction(Request $request, $uriFile) { 


    $filename = $uriFile; 
    $path = $this->getParameter('documents_directory').'/'.$filename; 

    $file = file_get_contents($path); 

    $response = new Response($file); 
    $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
    $response->headers->set('Content-Description', 'File Transfer'); 
    $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"'); 
    return $response; 

} 

的問題是,該文件被下載時,文件的格式不正確。例如,如果我上傳包含test字的docx,當我下載這個文件,我得到一個奇怪的.docx開始!

PK>¸ï7f[CONTENT_TYPES] .XML¢(†¥TÀn¬0ºWÍ? DæVâ°的™™˙8∂H•Ï XıKˆÚ˙˚nDUA*Â)YÔÃÏσɗ⁄öl 1iÔJ÷/z,'Ω「nV≤è…K~œ≤Ѭ)aºÉím ±—˙j0ŸHuªT≤9bx‡<…9Xë ¿Q•Ú— §◊8„A»O1~€Î›qÈÇ√k6<A%≥Á5}fi*âÀΣkÆíâåñI)_:IE%FL1' ŸúIs「

如果我轉換這個陌生的docx文件爲PDF格式,使用例如:https://online2pdf.com/en/convert-docx-to-pdf我得到一個test PDF字裏面,所以信息是在裏面,但它沒有正確顯示。

我的Symfony上傳控制器似乎工作得很好,因爲我可以從服務器訪問文件,並正確查看內容。

回答

0

您必須返回二進制響應。 你有兩次選擇此:

$fileName = 'your_docx.docx'; 
$path = $this->getParameter('documents_directory').'/'.$filename; 
$content = file_get_contents($path); 

$response = new Response(); 
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename); 
$response->setContent($content); 
return $response; 

參見:https://stackoverflow.com/a/30254080/6635967

的另一種方法是:

$fileName = 'your_docx.docx'; 
    $temp_file = $this->getParameter('documents_directory').'/'.$filename; 
    $response = new BinaryFileResponse($temp_file); 
    $response->setContentDisposition(
     ResponseHeaderBag::DISPOSITION_ATTACHMENT, 
     $fileName 
    ); 

    return $response; 

這裏找到:http://ourcodeworld.com/articles/read/361/how-to-create-a-word-file-with-php-in-symfony-3