这是从服务器下载文档的服务:
$app->get('/docDownload', function () use ($app){
$path = "/xxx/xxx/works.pdf";
$res = $app->response();
$res['Content-Description'] = 'File Transfer';
$res['Content-Type'] = 'application/pdf';
$res['Content-Disposition'] ='attachment; filename=' . basename($path);
$res['Content-Transfer-Encoding'] = 'binary';
$res['Expires'] = '0';
$res['Cache-Control'] = 'must-revalidate';
$res['Pragma'] = 'public';
$res['Content-Length'] = filesize($path);
readfile($path);
});
答案在这里
%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 8 0 R>>/ExtGState<</GS7 7 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 224>>
stream
x���Kk�0����9J�����`|�� �@����J�C
M!��$��bA,�ш]T�h�j��V0]���r���0��8R0L.F����70�3�}�8'�08L�V�Q��+�')��g��U;��V
��8�o�����o��Ip�I}�W_�r}��N'mգU��g>Ö�Ӎ���n>�D��.�-����<H`��ABC'ǐ'�=��ٻXwc�z��wx�
endstream
endobj
5 0 obj
<</Type/Font/Subtype/TrueType/Name/F1/BaseFont/ABCDEE+Calibri/Encoding/WinAnsiEncoding/FontDescriptor
6 0 R/FirstChar 32/LastChar 119/Widths 24 0 R>>
endobj
6 0 obj
<</Type/FontDescriptor/FontName/ABCDEE+Calibri/Flags 32/ItalicAngle 0/Ascent 750/Descent -250/CapHeight
750/AvgWidth 521/MaxWidth 1743/FontWeight 400/XHeight 250/StemV 52/FontBBox[ -503 -250 1240 750] /FontFile2
22 0 R>>
endobj
...... continues ........
我希望当WS被调用时,自动返回一个PDF文档,在用户屏幕上打开或带有保存或打开的选项。
我有一个方法在javascript中做到这一点:
var request = new XMLHttpRequest();
request.open("GET", "/documents/docDownload", true);
request.responseType = "blob";
request.onload = function (e) {
if (this.status === 200) {
// `blob` response
//console.log(this.response);
// create `objectURL` of `this.response` : `.pdf` as `Blob`
var file = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
a.href = file;
a.download = this.response.name || "detailPDF";
document.body.appendChild(a);
a.click();
// remove `a` following `Save As` dialog,
// `window` regains `focus`
window.onfocus = function () {
document.body.removeChild(a)
}
};
};
request.send();
是否有另一种方法在JQuery中做到这一点?
WS的反应是什么样的?
对我来说,你可以这样做jQuery.ajax()
:
$.ajax({
url: "/documents/docDownload",
type: "GET",
headers: {
responseType: "blob"
},
success: function(data) {
var file = window.URL.createObjectURL(data);
var a = $("<a/>", {
"href": file,
"download": data.name || "detailPDF"
}).appendTo('body');
a.click();
$(window).on('focus', function(e) {
$('a').remove();
});
}
})