1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sadkiviek
  • 11
  • 2
  • [https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api](https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api) – lbsn Oct 18 '21 at 15:04
  • There is no `files` property in the [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) options object – lbsn Oct 18 '21 at 15:06
  • I tried using body instead of files and it doesn't work. Flask request doesn't have a body – sadkiviek Oct 18 '21 at 15:09
  • I'm not a Flask user but this answer could be useful: [https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request) – lbsn Oct 18 '21 at 16:21
  • Thx I think I understand now – sadkiviek Oct 19 '21 at 07:29

1 Answers1

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);
},
sadkiviek
  • 11
  • 2