我正在使用 ilovepdf Rest api 和 php,我上传一个 pdf 文件,然后压缩并将其保存在我的服务器中。 但我想要的是在最后一个任务完成后将压缩文件自动下载到用户默认路径浏览器。 压缩文件名不是上传的文件名和idk为什么。 下面的代码下载无法打开的损坏文件,并在控制台中给出此错误:未捕获(承诺中)错误:侦听器通过返回 true 指示异步响应,但消息通道在收到响应之前关闭。 如何解决这个问题?我希望该文件以与上传文件相同的名称下载给用户,而不是保存在我的服务器中或至少在用户下载后删除。
<?php
// include the autoloader
require_once('../vendor/autoload.php');
// if manual installation has been used, comment the line that requires the autoload and uncomment this line:
// require_once('../init.php');
use Ilovepdf\CompressTask;
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Check if the file was uploaded without errors
if (isset($_FILES["pdf_file"]) && $_FILES["pdf_file"]["error"] === 0) {
// Get the temporary file name and original name of the uploaded file
$tempFileName = $_FILES["pdf_file"]["tmp_name"];
$originalFileName = $_FILES["pdf_file"]["name"];
// Move the uploaded file to a desired location (optional, you can keep it in the same location)
$destination = __DIR__ . '/' . $originalFileName;
if (move_uploaded_file($tempFileName, $destination)) {
// You can get your key pair from https://developer.ilovepdf.com/user/projects
$myTask = new CompressTask('public_key', 'secret_key');
// Add the file from user input to the task
$file = $myTask->addFile($destination, $originalFileName);
// Process the files
$myTask->execute();
// Download the compressed file
$myTask->download();
header("Content-Disposition: attachment; filename=\"" . $originalFileName . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($file));
header("Connection: close");
//handling errors
} else {
echo "Error moving the uploaded file.";
}
} else {
echo "Error uploading the file.";
}
}
?>
我还没有以任何方式尝试过这段代码,但是看来你可以只在任务上设置
$outputFileName
,然后调用 toBrowser()
方法,这样你就不必再费力了任何标头。在那里添加一个 try/catch 可能是一个好主意。
$myTask = new CompressTask('public_key', 'secret_key');
$myTask->addFile($destination, $originalFileName);
$myTask->execute();
$myTask->outputFileName = $originalFileName;
$myTask->toBrowser();