Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 224
Ashish Gupta Avatar asked Dec 18 '22 16:12

Ashish Gupta


1 Answers

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']
like image 100
Ashish Gupta Avatar answered Dec 20 '22 05:12

Ashish Gupta