Skip to content
Advertisement

How to get full filepath on Flask?

I want to get a full file path on Flask.

This is part of HTML code.

<form method="post" action="{{ url_for('xxx') }}" enctype='multipart/form-data'>
  <dl>
    <label for="fname">Filename</label>
    <input type="file" name="fname" id="fname">
  </dl>
  ...
</form>

Then, user sends the file name to Flask.

Flask will catch it.

try:
  file = request.files['fname']
  with open(file.filename) as f:
    ...
catch:
  ...

But Flask can only get the filename, not a full path.

So, this application can’t open the file and return the Internal Server Error.

How can I get the full path of the user’s local file?

Thanks in advance.

Advertisement

Answer

Basing off your question, I think you want to upload a file then access the uploaded file.

Few things is not clear though as you are asking about the full path of user’s local path which is not relevant to this task as flask should not have access to the user’s filesystem (except for browsing) and also, every user must define a different path per upload. So going back, I think the approach should be more of accessing the uploaded file of the user on the server.

So if this is the case, let me explain further.

Each uploaded file is first saved on a temporary location on the server, and then will actually be saved to its final location.

You can set this location via:

app.config['UPLOAD_FOLDER']

Of course the filename is the filename you get on the upload, based on your code.

Once set, just use the location and update your function.

Good reference can be found here: Consuming public uploads https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement