Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
How can I send a XML from HTML in string to Python (using Flask) using Fetch API in Javascript

I'm designing an app that receives an XML file from an HTML page and send it to Python using Flask This is my HTML (frontend) code

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

And I am using Flask with Python to run my backend, I am using POSTMAN (i show it below) and I send an XML on it and return what is supposed to return This is my Python code

@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',})

but I don't know how to send the XML data from the HTML file and make it work with my Python Backend, I have used Fetch before but no for this particular case This is my JavaScript code where I have confusion

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

What I can do? This is my program tested with POSTMAN

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Consider the following 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>

This is based on the following Example: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

When the User clicks Send, the file is sent to the function. New Form Data is created and POST to the server.

You may need to adjust your Python. See here: Get the data received in a Flask request

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda