在python Flask应用程序中使用json对象上传文件的POST方法 [英] POST method to upload file with json object in python flask app
问题描述
我遇到了一个问题,我正在尝试构建单个 API,该 API 将上传文件和 json 对象.我需要这个 API 来创建 webhook.
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.
使用多部分,我可以上传文件,在选项文件中我可以发送 json 对象.
Using multi part, I am able to upload file and in option filed I am able to send json object.
在 Flask 应用程序中,当我尝试检索 json 对象时,将其转换为 blob 类型.我尝试将其转换为 base64,然后再次转换为字符串,但整个过程不起作用.
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.
如果有人有好的解决方案,请告诉我,我可以将文件和 json 对象组合在一起,并通过 Flask python 应用程序获取它.
Let me know if anyone has good solution I can combine file and json object together and fetch it by flask python app.
zz 是我的代码中的变量,我试图在其中存储我的 json 对象.name 是我将 json 对象与文件一起传递的字段.
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.
提前致谢.
我当前的代码
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)
推荐答案
经过大量研发,我得到了答案.
I have got the answer after lot R&D.
请求格式
//user any client-side
content-type:multipart/form-data
file: file need to upload
data: {"name":"abc","new_val":1}
从请求对象中获取的python代码
data=json.loads(request.form.get('data'))
file = request.files['file']
这篇关于在python Flask应用程序中使用json对象上传文件的POST方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!