I'm using ilovepdf rest api with php, im uploading a pdf file then compress and saving it in my server. But what i want is the compressed file to be downloaded automaticly to the user default path browser after the last task is finished. The compressed file name not as the uploaded file name and idk why. This code below download damage file that can't be open , and in the console gives this error: Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received. How to slove this? i want the file to be downloaded to the user with the same name of the uploaded file , and not to be saved in my server or at least be deleted after the user download it .
<?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.";
}
}
?>
I haven't tried this code in any way, however it appears that you can just set the $outputFileName
on the task and then call the toBrowser()
method, and you won't have to mess around with any of the headers. Adding a try/catch in there would probably be a good idea.
$myTask = new CompressTask('public_key', 'secret_key');
$myTask->addFile($destination, $originalFileName);
$myTask->execute();
$myTask->outputFileName = $originalFileName;
$myTask->toBrowser();
exit;