1

私はここで答えを見つけました: Serving .docx files through Php しかし、php 経由で docx サーバーをダウンロードして開こうとすると、ファイルが破損しているというエラーが引き続き表示されます。.doc は正常に動作しますが、失敗したのは docx です。

$parts = pathinfo($doc);
$docFile = $userDocRoot.$doc;
if ( !file_exists($docFile) ){
    throw new Exception("Can not find ".$parts ['basename']." on server");
}
if ( $parts['extension'] == 'docx' ){
    header('Content-type: application/vnd.openxmlformats- officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="'.$parts['basename'].'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($docFile);
}else{
   header('Content-type: application/msword');
   header('Content-Disposition: attachment; filename="'.$parts['basename'].'"');
   readfile($docFile);
}
4

5 に答える 5

3

私にとっての解決策は追加することでした

 $fsize = filesize($docFile);
 header("Content-Length: ".$fsize);

みんなの助けに感謝

于 2012-08-21T20:44:03.320 に答える
2

コードに余分なスペースがいくつかあったため、失敗しました。

このコードを使用してみてください:

$parts = pathinfo($doc);
$docFile = $userDocRoot . $doc;
if(!file_exists($docFile)){
    throw new Exception('Can not find ' . $parts['basename'] . ' on server');
}
if($parts['extension'] == 'docx') {
    header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $parts['basename'] . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($docFile);
} else {
    header('Content-type: application/msword');
    header('Content-Disposition: attachment; filename="' . $parts['basename'] . '"');
    readfile($docFile);
}

headerそれでもうまくいかない場合は、行と行をコメントアウトしてみてreadfileください。エラーがあるかどうかを確認できます。

また、パスワードを含む PHP ファイルをダウンロードできないように、ファイル名をホワイトリストと照合することをお勧めします。

于 2012-08-21T20:23:25.543 に答える
1

DOCXファイルが破損していて、これに遭遇した理由をしばらく調べたところですが、他の場所でも答えを見つけました...

$fsize = filesize($docFile);
header("Content-Length: ".$fsize);

これは私に探すためのツールを与えてくれました...そして重要なのはfilesize()正確なファイルサイズを得るためにファイルのベースネームが必要なことです!

私のコードを適応させる:

header("Content-Length: ".filesize(basename($file)));

これにより、意図したとおりにDOCX(Content-typeを "application / vnd.openxmlformats-officedocument.wordprocessingml.document"に設定)が提供されるようになり、他の人が報告したようにドキュメントを「修復」する必要がなくなりました...(私も修復が機能したことがわかりました)

于 2012-11-08T15:44:55.847 に答える