3

I have a Python web application that runs locally in a web browser for interface convenience, processes files that a user selects, and saves processed data. I need to add the feature that creates a new subdirectory in the same folder where the file was selected (i.e., if the file is path/fname.txt, I need to create path/fname/ where I can put processed data). How do I access this path to the file?

In other projects I have asked for the path separately, but that's clunky and I'd rather not make the user do this extraneous step for each file.

@app.route('/getthefile', methods=['POST'])
def getthefile():
    file = request.files['myfile']
    filename = secure_filename(file.filename)
    new_path = os.path.abspath(filename)
    # gives me the wrong path
davidism
  • 121,510
  • 29
  • 395
  • 339
K Hutch
  • 113
  • 2
  • 3
  • 13

1 Answers1

5

In order to not expose unnecessary information about the client's system, only the filename is sent with the HTTP request. The full path is not sent. Take a look at an HTTP multipart/form-data request:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--

As you can see, information is pretty minimal. The path is not provided.

Similarly, the File API only allows access the filename.

So unfortunately, you won't be able to get the full path from a file input.

Theron Luhn
  • 3,974
  • 4
  • 37
  • 49