流式传输PDF文件的Web服务:
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: public');
header("Content-length: " . $filesize);
header('Content-Description: File Transfer');
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename={$name}");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: max-age=0');
ob_start();
fpassthru($fp);
$response = ob_get_contents();
ob_end_clean();
return $response;
启动请求并使用响应的jQuery代码:
$.ajax({
url: "/xxx/xxx/1/xxx/5",
type: "GET",
async: true,
dataType: 'binary',
headers:{'Content-Type':'application/pdf',
'X-Requested-With':'XMLHttpRequest',
},
processData: false,
success: function(data,status,xhr) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "Testing.pdf";
document.body.appendChild(a);
a.click();
$(window).on('focus', function(e) {
$('a').remove();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("fail");
}
PDF文件生成完美,并自动打开。这里唯一的问题是,当应该有文本时,PDF内容会变空!
有人知道为什么会这样吗?