-1

私はphpWordを使用して、XMLHttpRequestを使用して呼び出されるphpスクリプトでその場でWord文書を作成しています。リクエストへの応答をトラップし、ユーザーにファイルをダウンロードするか開くように求めようとしています。私のphpWordコードはファイルを正常に作成し(サーバー上のファイルを開くことができます)、ブラウザはユーザーにファイルを開くか保存するように求めますが、ダウンロードされたファイルは何らかの形で破損しています. 「申し訳ありません。結果の内容に問題が見つかったため、results.docx を開けません」のようなエラーが表示されます。

サーバー側には、次のコードがあります。

...
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document' );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);

クライアント側には、次のコードがあります。

function getDOC()
{
    url='services/doc_search_results_service.php/';

    var req = null;
    var postParms = '';

    req = new XMLHttpRequest
    if ( req )
    {
        req.open( 'POST', url, true );
        req.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
        req.setRequestHeader( "Content-length", postParms.length );
        req.setRequestHeader( "Connection", "close" );
        req.onreadystatechange = function()
        {
            if ( req.readyState == 4 && req.status == 200 )
            {
                downloadDOC( "results.docx", req.responseText );
            }
        }
        req.send( postParms );
    }
}

function downloadDOC(filename, text) 
{
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    document.body.appendChild(pom);
    pom.click();
    document.body.removeChild(pom);
}

誰かが私が間違っている場所を見つけることができるかどうか知りたい. 私はphpやjavascriptの専門家ではないので、どんな助けでもありがたいです. FWIW ヘッダーに関係していると思います。ファイルはサーバー側で正常に作成されるため、クライアント側の問題である可能性もあると推測しています。

前もって感謝します。:-)

4

1 に答える 1