2017-04-12 20 views
0

.docxファイルをアップロードするSymfonyコントローラと、ダウンロードするSymfonyコントローラがあります。ファイルをダウンロードする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; 

} 

問題は、ファイルがダウンロードされるとき、ファイルの形式が正しくないことです。例えば、私は、このファイルをダウンロードするとき、私は始まる奇妙な.docxを取得し、test単語を含むdocxファイルをアップロードする場合:!

PK>¸ï7f[CONTENT_TYPES](†¥TÀn¬0ºWÍ¢.xmlの?ディーヴァ°á™™˙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「

私は、たとえば使用して、PDFにこの奇妙なのdocxファイルを変換する場合: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

関連する問題