简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM