Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
Enviar pdf (o cualquier archivo) en una solicitud POST como cadena json y luego escribirlo por fs

Estoy creando un sitio web y necesito hacer un servidor POST backend. Creé el 90%, pero el problema al que me enfrento es que necesito enviar JSON y un pdf (normalmente enviado por multipart/form-data, pero necesitaría una ruta diferente). Lo que estoy tratando de hacer es transformar el archivo en base64string, enviarlo en una solicitud y luego restaurarlo y escribirlo en un archivo. Todo esto sucede, y el PDF incluso devuelve datos codificados, pero el PDF es solo una página en blanco cuando se escribe, incluso después de volver a convertirse a binario y escribirse.
Código JS del lado HTML:

 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; } };*/ }

Devolución de llamada JS del lado del servidor:

 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); })

Todo esto devuelve archivos PDF 100% en blanco (con un tamaño de archivo más grande que el original por alguna razón) sin importar qué PDF cargue
Por favor ayuda
Si conoce alguna otra forma de hacer lo que quiero decir en una solicitud y ruta, ¡díganos!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¡Encontré la respuesta!
tuve que cambiar

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

a

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

Y esto solucionaría el problema.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!