POST method to upload file with json object in python flask app POST method to upload file with json object in python flask app flask flask

POST method to upload file with json object in python flask app


I have got the answer after lot R&D.

request format

//user any client-sidecontent-type:multipart/form-data file: file need to upload  data: {"name":"abc","new_val":1}

python code to fetch from request object

data=json.loads(request.form.get('data'))file = request.files['file']


Just send the file and json at once and let request handle the rest.You can try the code below:

Server side:

import json                                                     import osfrom flask import Flask, requestfrom werkzeug import secure_filenameapp = Flask(__name__)                                           @app.route('/test_api',methods=['GET','POST'])            def test_api():                                               uploaded_file = request.files['document']    data = json.load(request.files['data'])    filename = secure_filename(uploaded_file.filename)    uploaded_file.save(os.path.join('path/where/to/save', filename))    print(data)    return 'success'if __name__ == '__main__':    app.run(host='localhost', port=8080)

Client Side:

import jsonimport requestsdata = {'test1':1, 'test2':2}filename = 'test.txt'with open(filename, 'w') as f:    f.write('this is a test file\n')url = "http://localhost:8080/test_api"files = [    ('document', (filename, open(filename, 'rb'), 'application/octet')),    ('data', ('data', json.dumps(data), 'application/json')),]r = requests.post(url, files=files)print(r)