Home > Net >  How to get filename from a file object in PYTHON?
How to get filename from a file object in PYTHON?

Time:10-21

I am using below code where I am using PUT api from POSTMAN to send a file to a machine hosting the api using python script

@app.route('/uploadFIle', methods=['PUT'])
def uploadFile():
    chunk_size = 4096
    with open("/Users/xyz/Documents/filename", 'wb') as f:
        while True:
            chunk = request.stream.read(chunk_size)
            if len(chunk) == 0:
                break
            f.write(chunk)
    return jsonify({"success":"File transfer initiated"})

Is there a way to get the original filename so that I can use the same while saving the file ?

Can do as below by passing name from PUT api itself, but is it the best solution ?

@app.route('/uploadFIle/<string:filename>', methods=['PUT'])
def uploadFile(filename):

CodePudding user response:

Below is how I achieved it using flask -

  1. Choose form-data under body in POSTMAN

  2. You can give any key, i used 'file' as key, then choose option 'file' from drop down arrow in key column

  3. Attach file under 'value' column and use below code to get the file name -

     from flask import request
     file = request.files['file']
     file_name = file.filename
    
  • Related