我使用PHP来获取它,因为我需要从另一台服务器下载PDF文件。要下载此文件,我需要登录,而客户端不必在那里登录。问题是用户得到的 PDF 文件只是一个白页。在我的服务器上,当我将其写入文件时,里面仍然有内容 ( file_put_contents("test.pdf",$content);)我在发送之前尝试对它进行 base64 编码,并认识到传递的数据仍然是正确的。因此它在解码 ( atob(data)) 或下载功能中失败。(我也试过 utf8 编码)在下载的pdf文件中,很多字符与这些框或问号( )交换。$result = curl_exec($ch);file_put_contents("test.pdf",$result); //test.pdf contains correct documentecho base64_encode($result);download(atob(data),"My.pdf") //data is answer of ajax requestfunction download(data, filename, type) { var file = new Blob([data], { type: type }); if (window.navigator.msSaveOrOpenBlob) // IE10+ window.navigator.msSaveOrOpenBlob(file, filename); else { // Others var a = document.createElement("a"), url = URL.createObjectURL(file); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); setTimeout(function () { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0); }}
2 回答
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
扬帆大鱼
TA贡献1799条经验 获得超9个赞
要显示 pdf(或任何其他文件类型),您必须在响应标头中设置内容类型等,以便浏览器正确解析并显示。这是我为向用户提供 pdf 内容而编写的一小部分代码。
$file = '/home/public_html/DriveMode/DRIVES/java.pdf'; //path to file
$filename = 'filename.pdf';
header('Content-type: application/pdf'); //setting content type in header
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file); // reads and writes the file to output buffer
希望这对您有所帮助,如果这里有什么令人困惑的地方,请在评论中告诉我。
添加回答
举报
0/150
提交
取消