[英]How to get the path of the posted file in Python
我正在從文件中獲取文件發布:
file = request.post['ufile']
我想得到路徑。 我怎么才能得到它?
你應該使用request.FILES['ufile'].file.name
你會得到這樣/var/folders/v7/1dtcydw51_s1ydkmypx1fggh0000gn/T/tmpKGp4mX.upload
並使用file.name
,您的上傳文件必須大於 2.5M。
如果要更改此設置,請參閱文件上傳設置
您必須使用request.FILES
字典。
查看有關UploadedFile
object 的官方文檔,您可以使用UploadedFile.temporary_file_path
屬性,但要注意只有上傳到磁盤的文件才會暴露它(即通常在使用TemporaryFileUploadHandler
上傳處理程序時)。
upload = request.FILES['ufile']
path = upload.temporary_file_path
但是,在正常情況下,您希望直接使用文件處理程序:
upload = request.FILES['ufile']
content = upload.read() # For small files
# ... or ...
for chunk in upload.chunks():
do_somthing_with_chunk(chunk) # For bigger files
我們無法從 post 請求中獲取文件路徑,只能獲取文件名,因為 flask 沒有文件系統訪問權限。 如果您需要獲取文件並對其執行一些操作,那么您可以嘗試創建一個臨時目錄將文件保存在那里,您也可以獲取路徑。
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.