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

241
Views
¿Cuál es el equivalente de Fetch API de XMLHttpRequest.send (archivo)?

Estoy tratando de refactorizar un cliente a un backend antiguo de XMLHttpRequest para usar la API Fetch en su lugar, y tengo dificultades para averiguar cuál es el equivalente de la API Fetch de xhr.send (archivo) en el código a continuación.

 input.addEventListener('change', function(event) { var file = event.target.files[0]; var url = 'https://somedomain.com/someendpoint'; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'image/jpeg'); xhr.send(file); }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

fetch puede tomar un segundo argumento , init , que especifica las opciones avanzadas de la solicitud. En particular, puede especificar el method y las opciones del body :

 fetch(url, { method: 'POST', headers: new Headers({ "Content-Type": "image/jpeg", }), body: file, })

También puede pasar las mismas opciones al constructor de Request .

El body debe ser un objeto Blob, BufferSource, FormData, URLSearchParams o USVString. Afortunadamente, los objetos de archivo son solo un tipo especial de blobs y se pueden usar en cualquier lugar donde se acepten blobs .

over 4 years ago · Santiago Trujillo Report

0

Esto se puede hacer así:

 var input = document.querySelector('input[type="file"]') var data = new FormData() data.append('file', input.files[0]) fetch('/avatars', { method: 'POST', body: data })

https://github.com/github/fetch

https://developer.mozilla.org/en-US/docs/Web/API/FormData

over 4 years ago · Santiago Trujillo 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!