Ashish Gupta
Ashish Gupta

Reputation: 392

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

I am stuck in a problem where I am trying to build single API which will upload file along with json object. I need this API to create webhook.

Using multi part, I am able to upload file and in option filed I am able to send json object.

In flask app when I am trying to retrieve json object its converting as blob type. I tried to convert it base64 then again converting into string but whole process is not working.

Let me know if anyone has good solution I can combine file and json object together and fetch it by flask python app.

zz is the variable in my code where I am trying to store my json object. name is the field where I am passing my json object with file.

Thanks in advance.

My current code

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/upload/',methods = ['POST'])
def upload():
    customer_name='abc'
    if request.method == 'POST':

        zz=base64.b64encode(request.files['name'].read())
        try:
            file = request.files['file']
            if file:
                file.filename=customer_name+'_'+str(datetime.now())+'.'+file.filename.split('.')[-1]
                filename = secure_filename(file.filename)
                path=os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(path)

            return jsonify({
                'status':success,
                'junk_data':[],
                'message':error
                })
        except Exception as err:
            logger.error(str(datetime.now())+' '+str(err))
            return jsonify({
                'status':False,
                'junk_data':[],
                'message':str(err)
                })
if __name__ == '__main__':
    app.run(host='localhost',debug=True, use_reloader=True,port=5000)

Upvotes: 6

Views: 17988

Answers (2)

Ashish Gupta
Ashish Gupta

Reputation: 392

I have got the answer after lot R&D.

request format

//user any client-side

content-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']

Upvotes: 11

Jethro Sandoval
Jethro Sandoval

Reputation: 286

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 os
from flask import Flask, request
from werkzeug import secure_filename

app = 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 json
import requests

data = {'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)

Upvotes: 7

Related Questions