Home > front end >  Sending pdf (or any file) over in a POST request as json string and then writing it down by fs
Sending pdf (or any file) over in a POST request as json string and then writing it down by fs

Time:10-11

I am creating a website and I need to make a backend POST server. I have created 90% of it, but the issue I am facing is that I need to send JSON as well as a pdf (normally sent by multipart/form-data, but would need a different route). What I am trying to do is transform the file into base64string, send it over in a request, and then restore it back and write it to a file. This whole thing happens, and the PDF even returns scrambled data, but the PDF is just a blank page when written down even after being converted back to binary and being written
HTML-side JS code:

async function post(endpoint){
    let binaryCV;
    let CV = document.getElementById("upfile").files[0];
        var reader = new FileReader();
        reader.onload = (readerEvt)=>{
            var binaryString = readerEvt.target.result;
            binaryCV = binaryString;
            let xhr = new XMLHttpRequest();
            let object = {
                name: document.getElementById("ecaName").value,
                email: document.getElementById("ecaEmail").value,
                phone: document.getElementById("ecaTel").value,
                class: document.getElementById("ecaClass").value,
                institute: document.getElementById("ecaInstitute").value,
                paragraph:{
                    experience: document.getElementById("ecaExp").value,
                    why: document.getElementById("ecaWhyPart").value,
                    changes: document.getElementById("ecaWhatChanges").value,
                },
                CV: binaryCV,
            }
            xhr.open("POST", `http://localhost:8080/apply/internship/${endpoint}`,true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify(object));
        };

        await reader.readAsBinaryString(CV);
    /*xhr.onload = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = xhttp.responseText;
        }
    };*/
}

Server side JS callback:

        app.post('/apply/internship/econoxe', async (req, res)=>{
            res.sendStatus(200);
            let CV = req.body.CV;
            fs.writeFileSync(path.join(__dirname,`../CV/${req.body.email}.pdf`),CV)
            console.log(req.body);
        })

All this returns 100% blank PDFs (with larger file size than original for some reason) no matter what PDF I upload
Please help
If you know any other way to do what I mean in one request and route, please tell!

CodePudding user response:

you can use FormData() to send any files to backend. use this instead FileReader() and append your data to it

const fromData = new FromData();
fromData.append("pdf", document.getElementById("upfile").files[0]);
fromData.append("email", document.getElementById("ecaEmail").value;

then post formData and get "pdf" in your post route from req.file or req.files.

CodePudding user response:

I found the answer!
I had to change

fs.writeFileSync(path.join(__dirname,`../CV/${req.body.email}.pdf`),CV)

to

fs.writeFileSync(path.join(__dirname,`../CV/${req.body.email}.pdf`),CV,"binary")

And this would fix the issue

  • Related