Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
Passing a header and a file in a javascript fetch POST request to a flask server

I'm trying to create a simple website to run a neural network on an image. The frontend is in VUE.js and the backend in python flask. I can pass the data I want like id and precision in the header, however, the file doesn't "upload" to the flask server. Any idea how I should be doing this?

This is my method in javascript:

async predictUF(img) {
  //let config = {header : {'Content-Type' : 'image/png'}}
  const response = await fetch("http://localhost:5000/process_img", {
      method: 'POST',
      headers: {'id': '123', 'precision': '75'},
      files: img,
      mode: 'cors',
      cache: 'default'
    });
    
  const recv = await response.json();
  console.log(recv);
},

And this is my flask server code:

@app.route('/process_img', methods=['POST', 'GET'])
@cross_origin()
def process_image():
    if request.method == 'POST':
        filenames = []
        payload = request.headers
        id = payload['id']
        precision = payload['precision']
        files = request.files.to_dict(flat=False)
        for file_list in files.values():
            for file in file_list:
                name = secure_filename(file.filename)
                path = save_image(file, name)
                filenames.append(path)

        results, img_paths = run_process(filenames)
        encoded_imgs = [encode_image(p) for p in img_paths]
        return jsonify({'msg': 'success', 'results': [results], 'images': encoded_imgs})
    else:
        return 'Methods restricted'

I had a python script to test the api that worked perfectly, it was something like this (I ignored the base64 encodings on purpose to simplify the problem):

r = requests.post(url, files=files, data=payload)

Is there any way to fill the files in the javascript fetch api or am I getting this all wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Thanks to Ibsn I got it working.

For flask to accept request.files: an HTML forms must be used with enctype=multipart/form-data. (How do I upload a file with the JS fetch API?)

Fortunately, javascript FormData() uses the same format a form would use if the encoding type were set to "multipart/form-data". So my final js working version is this. (Get the data received in a Flask request)

async predictUF(img) {
  var data = new FormData();
  data.append('files', img, img.name);
  const response = await fetch("http://localhost:5000/process_img", {
      method: 'POST',
      headers: {'id': '123', 'precision': '75'},
      body: data,
      mode: 'cors',
      cache: 'default'
    });
    
  const recv = await response.json();
  console.log(recv);
},
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda