My current challenge involves the necessity of sending data to a server in JSON format exclusively, and I also need to include a PDF file along with other form data within the JSON. Initially, I attempted to convert the PDF into a base64 string following a similar approach outlined in this solution that I stumbled upon on SO:
let data = {foo: 1, bar: 2};
let reader = new FileReader();
reader.readAsDataURL(pdf);
reader.onload = () => {
data.file = reader.result;
$.ajax({type: 'POST', dataType: "json", data: JSON.stringify(data), ...});
}
To my dismay, it turned out that reader.result
does not encompass the entire PDF content (whether saved to file or retrieved from the server). While the text editor displays consistent content, a binary analysis reveals missing bytes. Although my browser manages to load it as a PDF and display the title, the page remains blank.
Despite experimenting with reader.readAsBinaryString
and converting it to base64 using btoa
, the outcome remained unaltered.
Edit: Link to CodePen example: https://codepen.io/jdelafon/pen/eRWLdz?editors=1011
Edit: To validate this, I performed the following:
let reader = new FileReader();
reader.readAsBinaryString(pdf);
reader.onload = () => {
let blob = reader.result;
let file = new Blob([blob], {type: 'application/pdf'});
let fileURL = window.URL.createObjectURL(file);
// render it within <embed>
};
The PDF's body appears empty. Substituting file
with the original pdf
enables complete display. Hence, FileReader seems to lose data in the process.
https://i.sstatic.net/0RL8d.png
Is there an improved method available? Could it be linked to an encoding complication with FileReader
?
I contemplated utilizing FormData like so:
let data = {foo: 1, bar: 2};
let fd = new FormData();
fd.append('file', pdf);
data.file = btoa(fd);
$.ajax({type: 'POST', dataType: "json", data: JSON.stringify(data), ...});
However, retrieving the data from the server poses a challenge since JavaScript fails to recognize it as a FormData object. Consequently, I am uncertain how to retrieve the file for browser rendering. Is there a feasible solution?