php下载pdf转存本地的实现方法:首先创建html页面代码以及script.js代码;然后创建本地读取pdf文件的PHP代码;最后把jquery库文件引进来,进行远程下载即可。

本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑
PHP ajax 远程下载PDF文件保存在本地服务器
在一些时候我们想ajax方式来保存一些PDF文件,尤其是它放在远程服务器上,并且是保存在我们自己的服务器上存储,这个时候我们需要写一段程序来帮助我们完成这个工作,本文介绍了PHP 远程下载PDF文件保存在本地服务器本地化,需要的朋友可以参考下:
html页面代码如下:
立即学习“PHP免费学习笔记(深入)”;
script.js代码如下:
$(function() {
$("button").click(function() {
$.ajax({
url: "http://lch.bat.com/aa.pdf",
type: "GET",
dataType: 'binary',
success: function(result) {
var blob = new Blob([result], {type:"application/pdf"});
var data = new FormData();
data.append('file', blob);
$.ajax({
type: 'POST',
url: 'http://lch.demo.com/read.php',
data: data,
processData: false,
contentType: false,
success: function (arg) {
alert('下载成功');
}
})
}
});
});
});jquery.binarytransport.js代码如下:
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
*
*/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
{
return {
// create new XMLHttpRequest
send: function(_, callback){
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null;
xhr.addEventListener('load', function(){
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, true);
xhr.responseType = dataType;
xhr.send(data);
},
abort: function(){
jqXHR.abort();
}
};
}
});再来看看我的本地读取pdf文件的代码:
最后把jquery库文件引进来,远程下载后,本地即可以打开和原始文件内容一模一样,不会出现乱码了。
推荐学习:《PHP视频教程》











