简体   繁体   English

Python中如何获取发布文件的路径

[英]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你应该使用request.FILES['ufile'].file.name

you will get like this /var/folders/v7/1dtcydw51_s1ydkmypx1fggh0000gn/T/tmpKGp4mX.upload你会得到这样/var/folders/v7/1dtcydw51_s1ydkmypx1fggh0000gn/T/tmpKGp4mX.upload

and use file.name , your upload file have to bigger than 2.5M.并使用file.name ,您的上传文件必须大于 2.5M。

if you want to change this, see File Upload Settings如果要更改此设置,请参阅文件上传设置

You have to use the request.FILES dictionary.您必须使用request.FILES字典。

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).查看有关UploadedFile object 的官方文档,您可以使用UploadedFile.temporary_file_path属性,但要注意只有上传到磁盘的文件才会暴露它(即通常在使用TemporaryFileUploadHandler上传处理程序时)。

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.我们无法从 post 请求中获取文件路径,只能获取文件名,因为 flask 没有文件系统访问权限。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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