简体   繁体   中英

How to get the path of the posted file in Python

I am getting a file posting from a file:

file = request.post['ufile']

I want to get the path. How can I get it?

You should use request.FILES['ufile'].file.name

you will get like this /var/folders/v7/1dtcydw51_s1ydkmypx1fggh0000gn/T/tmpKGp4mX.upload

and use file.name , your upload file have to bigger than 2.5M.

if you want to change this, see File Upload Settings

You have to use the request.FILES dictionary.

Check out the official documentation about the UploadedFile object , you can use the UploadedFile.temporary_file_path attribute, but beware that only files uploaded to disk expose it (that is, normally, when using the TemporaryFileUploadHandler uploads handler).

upload = request.FILES['ufile']
path = upload.temporary_file_path

In the normal case, though, you would like to use the file handler directly:

upload = request.FILES['ufile']
content = upload.read()  # For small files
# ... or ...
for chunk in upload.chunks():
    do_somthing_with_chunk(chunk)  # For bigger files

We cannot get the file path from the post request, only the filename, because flask doesn't has the file system access. If you need to get the file and perform some operations on it then you can try creating a temp directory save the file there, you can also get the path.

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# perform some operations if needed
shutil.rmtree(dirpath) # remove the  temp directory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM