狐的傳說
2021-09-30 19:20:38
我使用PHP來獲取它,因為我需要從另一臺服務(wù)器下載PDF文件。要下載此文件,我需要登錄,而客戶端不必在那里登錄。問題是用戶得到的 PDF 文件只是一個白頁。在我的服務(wù)器上,當我將其寫入文件時,里面仍然有內(nèi)容 ( file_put_contents("test.pdf",$content);)我在發(fā)送之前嘗試對它進行 base64 編碼,并認識到傳遞的數(shù)據(jù)仍然是正確的。因此它在解碼 ( 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 回答

揚帆大魚
TA貢獻1799條經(jīng)驗 獲得超9個贊
要顯示 pdf(或任何其他文件類型),您必須在響應(yīng)標頭中設(shè)置內(nèi)容類型等,以便瀏覽器正確解析并顯示。這是我為向用戶提供 pdf 內(nèi)容而編寫的一小部分代碼。
$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
提交
取消