Tfi*_*ish 0 javascript php pdf url
我在用 JavaScript 读取二进制数据流时遇到了一些困难。
当前,会弹出一个窗口并显示无法加载 PDF 文档。我将在下面发布我的回复和代码,任何帮助将不胜感激。
这是我的后端 PHP:
function getPDF() {
$file = __DIR__.'\..\pdf\FAS_HeadedPaper.pdf';
header("Content-Length: " . filesize ( $file ) );
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=".basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
ob_clean();
flush();
readfile($file);
}
Run Code Online (Sandbox Code Playgroud)
这是我的前端 JavaScript 控制器:
$scope.sendRef = function(ref){
$http({
method: 'GET',
url: $scope.endpoint + 'attachments/PDF',
async: true,
headers: {
'Authorization': 'MyToken'
},
params: {
ref: ref
},
dataType:'blob'
})
.success(function (data) {
console.log(data);
var file = new Blob([(data['response'])], {type: 'application/pdf'});
//var file = data['response'];
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
$scope.content = $sce.trustAsResourceUrl(fileURL);
})
.error(function (data, status) {
console.log('Error: ' + status);
console.log(data);
});
}
Run Code Online (Sandbox Code Playgroud)
这只是我在浏览器控制台中得到的响应片段:
%PDF-1.5
%????
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 14 0 R/MarkInfo<</Marked true>>>>
endobj
2 0 obj
<</Type/Pages/Count 1/Kids[ 3 0 R] >>
endobj
3 0 obj
<</Type/Page/Parent 2 0 R/Resources<</Font<</F1 5 0 R/F2 7 0 R/F3 9 0 R>>/XObject<</Image11 11 0 R>>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>/Tabs/S/StructParents 0>>
endobj
4 0 obj
<</Filter/FlateDecode/Length 917>>
stream
x??V[O?X~???p?V>??eUU[B
?J?B???J?-?S?H???? -??Y???????'??E1k?????-f7??]??z?%?~??E?\UE???7o???O????dR?0l?$?'?v,
V??z8 ?PL?????e?r????pp?E6.?6?0L?`?*<?}?5 Q??)???.k?Hgu?m???dc|h????&???x????{GIY?L??d
??e??LMd??b?i??~e%??X???\?l:C~)P%=??????\g7+14)^??} ????~?+.m??2"-?w?Q??? KZKP??Su?=???
Run Code Online (Sandbox Code Playgroud)
我实际上修复了它,以便它可以在我需要的时候工作!
我responseType: 'arraybuffer',在 blob 之前添加 了它,然后在成功中将其称为应用程序/pdf,并且运行良好。
$scope.sendRef = function(ref){
$http({
method: 'GET',
url: $scope.endpoint + 'attachments/PDF',
async: true,
headers: {
'Authorization': 'MyToken'
},
params: {
ref: ref
},
responseType: 'arraybuffer',
dataType:'blob'
})
.success(function (data) {
console.log(data);
var file = new Blob([(data['response'])], {type: 'application/pdf'});
//var file = data['response'];
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
$scope.content = $sce.trustAsResourceUrl(fileURL);
})
.error(function (data, status) {
console.log('Error: ' + status);
console.log(data);
});
}
Run Code Online (Sandbox Code Playgroud)