我正在使用phpWord在php脚本中动态创建一个word文档,该脚本使用XMLHttpRequest调用。我正在捕获对请求的响应,然后尝试提示用户下载或打开文件。 我的phpWord代码创建文件OK(我可以在服务器上打开文件),浏览器提示用户打开或保存文件,但下载的文件以某种方式损坏。它给出一个错误,例如"很抱歉。我们无法打开结果.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 我认为这可能与标题有关。 我也猜测这很可能是客户端问题,因为文件在服务器端创建正常。
提前谢谢。
感谢@Musa建议使用"GET"而不是"POST",效果很好。
正如@Musa所建议的,这个例子中的客户端javascript应该是:
window.location = 'services/doc_search_results_service.php/';
它取代了我原始问题中引用的所有 javascript。
注意 - 如果由于某种原因无法使用 GET,我不确定正确的答案会是什么。