• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

344
Views
¿Cómo puedo enviar un XML desde HTML en cadena a Python (usando Flask) usando Fetch API en Javascript?

Estoy diseñando una aplicación que recibe un archivo XML de una página HTML y lo envía a Python usando Flask Este es mi código HTML (interfaz)

 <input type="file" id="files" class="form-control" accept=".xml" required /> <button onclick="send()" style="width: 150px;" class="btn btn-primary">Send</button>

Y estoy usando Flask con Python para ejecutar mi backend, estoy usando POSTMAN (lo muestro a continuación) y le envío un XML y devuelvo lo que se supone que debe devolver . Este es mi código de Python

 @app.route('/Students', methods=['POST']) def loaddata(): # this is a list global dataArray entry= request.data.decode('utf-8') xmlentry= ET.fromstring(entry) for student in xmlentry.findall('STUDENT'): name= dte.find('NAME').text address = dte.find('ADDRESS').text new = DataObject(name,adress) # DataObject its a class, i am using OOP dataArray.append(new) return jsonify({'Mensaje':'Students added to the database',})

pero no sé cómo enviar los datos XML del archivo HTML y hacer que funcione con mi Python Backend, he usado Fetch antes pero no para este caso en particular Este es mi código JavaScript donde tengo confusión

 var file1 = document.getElementById("file"); function send() { fetch('localhost:3000/Students', { method: 'POST', body: file1, headers:{ 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*',}}) .then(res => res.json()) .catch(err => { console.error('Error:', err) alert("Ocurrio un error, ver la consola") }) .then(response =>{ console.log(response); alert(response.Mensaje) }) }

¿Que puedo hacer? Este es mi programa probado con POSTMAN

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Considere el siguiente HTML/JavaScript.

 function send(file) { var formData = new FormData(); formData.append('xmlFile', file); fetch('localhost:3000/Students', { method: 'POST', body: formData, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*', } }) .then(res => res.json()) .catch(err => { console.error('Error:', err) alert("Ocurrio un error, ver la consola") }) .then(response => { console.log(response); alert(response.Mensaje) }) } var fileInp = document.getElementById("files"); var sendBtn = document.getElementById("filesBtn"); sendBtn.addEventListener('click', (event) => { if (fileInp.files[0] !== undefined) { send(fileInp.files[0]); } else { alert("Please select a XML File."); } });
 <input type="file" id="files" class="form-control" accept=".xml" required /> <button id="filesBtn" style="width: 150px;" class="btn btn-primary">Send</button>

Esto se basa en el siguiente ejemplo: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

Cuando el usuario hace clic en Enviar, el file se envía a la función. Se crean nuevos datos de formulario y POST al servidor.

Es posible que deba ajustar su Python. Ver aquí: Obtener los datos recibidos en una solicitud Flask

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error