解決django FileFIELD的編碼問題
當獲取FileField數據時會出現編碼問題
在數據庫里顯示的是D:python項目wxmkczpyuploadfileQQ截圖20190210180915.png
而取出后變成
D%3A/python%E9%A1%B9%E7%9B%AE/wxmkczpy/uploadfile/QQ%E6%88%AA%E5%9B%BE20190210180915.png
這是url編碼
所以可以用urllib 的parse模塊解決
from urllib import parse # Create your tests here.a = 'D%3A/python%E9%A1%B9%E7%9B%AE/wxmkczpy/uploadfile/QQ%E6%88%AA%E5%9B%BE20190210180915.png'str3 = parse.unquote(a) #解碼字符串print(str3)
'C:Program FilesPython36python.exe' D:/python項目/wxmkczpy/wechat_app/tests.pyD:/python項目/wxmkczpy/uploadfile/QQ截圖20190210180915.png
補充知識:Django中FilePathField字段的使用
class FilePathField(path=None[, match=None, recursive=False, max_length=100, **options])
一個 CharField ,內容只限于文件系統內特定目錄下的文件名。有三個參數, 其中第一個是 必需的:
FilePathField.path
必填。這個FilePathField 應該得到其選擇的目錄的絕對文件系統路徑。例如: '/home/images'.
FilePathField.match
可選的.FilePathField 將會作為一個正則表達式來匹配文件名。但請注意正則表達式將將被作用于基本文件名,而不是完整路徑。例如: 'foo.*.txt$', 將會匹配到一個名叫 foo23.txt 的文件,但不匹配到 bar.txt 或者 foo23.png.
FilePathField.recursive
可選的.True 或 False.默認是False.聲明是否包含所有子目錄的路徑
FilePathField.allow_files
可選的.True 或 False.默認是True.聲明是否包含指定位置的文件。該參數或allow_folders 中必須有一個為 True.
FilePathField.allow_folders
是可選的.輸入 True 或者 False.默認值為 False.聲明是否包含指定位置的文件夾。該參數或 allow_files 中必須有一個為 True.
當然,這些參數可以同時使用。
有一點需要提醒的是 match只匹配基本文件名(base filename), 而不是整個文件路徑(full path). 例如:
FilePathField(path='/home/images', match='foo.*', recursive=True)
...將匹配/home/images/foo.png而不是/home/images/foo/bar.png 因為只允許匹配 基本文件名(foo.png 和 bar.png).
FilePathField實例被創建在您的數據庫為varchar列默認最大長度為 100 個字符。作為與其他字段,您可以更改使用的max_length最大長度。
大多數網站在插入圖片時一般都是這樣處理的:
上傳大尺寸圖時,自動生成一張縮略圖;網頁中插入縮略圖,并把地址指向大尺寸的圖。
所以在Django中,我這樣定義主要字段:
title = models.CharField(max_length = 120)img = models.ImageField(upload_to = ’screenshots’)thumb = models.FilePathField(path = ’screenshots/thumb’)
為什么thumb不是ImageFiled呢?因為考慮到Admin中上傳的是大圖,而縮略圖不是上傳,而是自動生成的。所以在這樣寫。具體的處理是(假設MEDIA_ROOT為/tmp,MEDIA_URL為http://localhost/media/:
上傳圖片(test.jpg)至MEDIA_ROOT/screenshots,此時img的屬性是:
img.name = screenshots/test.jpg, img.path = /tmp/screenshots/test.jpg, img.url = http://localhost/media/screenshots/test.jpg
判斷圖片大小是否需要做縮略圖,如果不需要,直接復制img.path到thumb,否則,生成一張縮略圖(以test-thumb.jpg命名)保存在screenshots/thumb下。
在網頁中插入圖片時,就可以簡單地用
<a href='http://www.wxshucaidpc.com/bcjs/{% object.img.url %}' rel='external nofollow' ><img src='http://www.wxshucaidpc.com/bcjs/{% object.thumb %}' alt='{% object.title %}'></a>
來表示了。object表示一個ScreenShot。
以上這篇解決django FileFIELD的編碼問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: