开发者

How to get the path of the posted file in Python

开发者 https://www.devze.com 2023-03-20 06:37 出处:网络
I am getting a file posting from a file: file = request.post[\'ufile\'] I wa开发者_如何学编程nt to get the path. How can I get it?You have to use the request.FILES dictionary.

I am getting a file posting from a file:

file = request.post['ufile']

I wa开发者_如何学编程nt to get the path. How can I get it?


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消