때때로 우리는 일부 PDF 파일을 ajax 모드로 저장하고 싶을 때가 있습니다. 특히 원격 서버에 배치하고 자체 서버에 저장하는 경우이 작업을 완료하는 데 도움이되는 프로그램을 작성해야합니다.이 기사에서는 PHP를 원격으로 소개합니다. PDF 파일을 다운로드하고 현지화를 위해 로컬 서버에 저장합니다. 필요한 친구는 다음을 참조 할 수 있습니다.
html 페이지 코드는 다음과 같습니다.
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="jquery.binarytransport.js"></script>
<script src="script.js"></script>
</head>
<body>
<button>download pdf</button>
</body>
</html>
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 파일을 읽기위한 내 로컬 코드를 살펴 보겠습니다.
<?php
/**
* Created by PhpStorm.
* User: LCA
* Date: 2020/9/28
* Time: 9:44
*/
//header('Access-Control-Allow-Origin: *');
// 响应类型
header('Access-Control-Allow-Methods:*');
// 响应头设置
header('Access-Control-Allow-Headers:content-type,token,id');
header("Access-Control-Request-Headers: Origin, X-Requested-With, content-Type, Accept, Authorization");
if(isset($_FILES['file'])){
$fname = "cc.pdf";
move_uploaded_file($_FILES['file']['tmp_name'], "/htdocs/demo/" . $fname);
echo "写入成功";
}
마지막으로 jquery 라이브러리 파일이 도입되어 원격 다운로드 후 로컬에서 열 수 있으며 원본 파일의 내용이 정확히 동일하며 문자가 깨지지 않습니다.