【发布时间】:2016-01-22 17:33:03
【问题描述】:
这是从服务器下载文档的服务:
$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 响应是什么样的?
【问题讨论】:
-
如果用javascript可以实现,为什么还要涉及jQuery?
-
真的!如果这对你有用,只要坚持下去,拥有另一个库的负载来解决同样的问题对我来说不是一个好主意,但回答它是的,你也可以使用 jQuery 来做到这一点。
-
所有其他使用此 Web 服务的平台都在使用 jquery 来发出 ajax 请求,如果可能的话,我想保留这种模式
-
在哪里可以在 jquery 中定义 responseType = "blob"?
标签: javascript php jquery pdf download