Python FLask Save Uploaded Files

Post last updated:2021-01-28

@app.route('/api/upload/', methods=['POST'])
def upload():
    #get file
    uploaded_file = request.files['file']
    #get file extension(file name -> request.files['file'].filename)
    file_extension = uploaded_file.filename.split('.')[-1]
    #get MIME type
    mimetype = uploaded_file.mimetype
    #set save target to current dir +'files/'
    save_target = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'files/', uploaded_file.filename)
    #create target if doesnt exist
    if not os.path.isdir(os.path.dirname(os.path.abspath(__file__)), 'files/'):
        os.mkdir(os.path.dirname(os.path.abspath(__file__)), 'files/')
    #save
    uploaded_file.save(save_target)
    #return can be anything
    return jsonify(
        code=200
    )

All content on this site uses CC BY-SA 4.0 license!