I am creating a PDF compressor tool via javascript. My pdf is uploaded, processed, and downloaded successfully. It shows the difference between the original size and the compressed size. Everything is working properly but when i try to open my compressed PDF it shows an error that unable to open the pdf file. I don’t know why this error occurs and how to resolve it.
here is the javascript code
document.getElementById('fileInput').addEventListener('change', function (e) {
const file = e.target.files[0];
if (file) {
compressPDF(file);
}
});
function compressPDF(file) {
const formData = new FormData();
formData.append('pdf', file);
document.getElementById('loader').style.display = 'block';
document.getElementById('progressContainer').style.display = 'block';
document.getElementById('progressBar').style.width = '0%';
const xhr = new XMLHttpRequest();
xhr.open('POST', '/compress-pdf', true);
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
document.getElementById('progressBar').style.width = percentComplete + '%';
}
};
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
if (response.success) {
const compressedPDF = response.fileUrl;
document.getElementById('pdfWrapper').style.display = 'block';
document.getElementById('pdfInfo').textContent = `Original Size: ${response.originalSize} MB, Compressed Size: ${response.compressedSize} MB`;
document.getElementById('downloadLink').href = compressedPDF;
} else {
alert('Failed to compress the PDF. Please try again.');
}
} else {
alert('Error occurred during the file upload. Please try again.');
}
document.getElementById('loader').style.display = 'none';
document.getElementById('progressContainer').style.display = 'none';
};
xhr.onerror = function () {
alert('An error occurred while uploading the file. Please try again.');
document.getElementById('loader').style.display = 'none';
document.getElementById('progressContainer').style.display = 'none';
};
xhr.send(formData);
}
I want to know if this code damaged my PDF file or why this error occurs.