template html(模板檔案):
<form
enctype
="multipart/form-data"
method
="post"
action
="/address/upload/"
>
<
input
type
="file"
name
="file"
/>
<
br />
<
input
type
="submit"
value
="上傳檔案"
/>
form
>
有如下乙個form:
from django importforms
class
uploadfileform(forms.form):
title = forms.charfield(max_length=50)
file = forms.filefield()
處理這個form的檢視收到了在request.files中的檔案資料。從上述form來的資料可以通過request.files['file']來訪問。
特別注意的是,只有當request方法是post,且傳送request的有屬性enctype="multipart/form-data"時,request.files中包含檔案資料,否則request.files為空。
以下檢視函式:
必須要將request.files傳給form的建構函式,才能將檔案資料繫結到form.
處理上傳檔案
字典request.files中的每乙個條目都是乙個uploadfile物件。uploadfile物件有如下方法:
1、uploadfile.read():
從檔案中讀取全部上傳資料。當上傳檔案過大時,可能會耗盡記憶體,慎用。
2、uploadfile.multiple_chunks():
如上傳檔案足夠大,要分成多個部分讀入時,返回true.預設情況,當上傳檔案大於2.5m時,返回true。但這乙個值可以配置。
3、uploadfile.chunks():
返回乙個上傳檔案的分塊生成器。如multiple_chunks()返回true,必須在迴圈中使用chrunks()來代替read()。一般情況下直接使用chunks()就行。
4、uploadfile.name():上傳檔案的檔名
5、uplaodfile.size():上傳檔案的檔案大小(位元組)
由上面的說明可以寫出handle_uploaded_file函式
defhandle_uploaded_file(f):
destination = open('
some/file/name.txt
', '
wb+'
)
for chunk in
f.chunks():
destination.write(chunk)
destination.close()
詳細點:
defhandle_uploaded_file(f):
file_name = ""
try:
path = "
media/editor
" + time.strftime('
/%y/%m/%d/%h/%m/%s/')
ifnot
os.path.exists(path):
os.makedirs(path)
file_name = path +f.name
destination = open(file_name, '
wb+'
)
for chunk in
f.chunks():
destination.write(chunk)
destination.close()
except
exception, e:
e
return file_name
上傳檔案儲存的位置
儲存上傳檔案前,資料需要存放在某個位置。預設時,當上傳檔案小於2.5m時,django會將上傳檔案的全部內容讀進記憶體。意味著儲存檔案只有一次從記憶體讀取,一次寫磁碟。
但當上傳檔案很大時,django會把上傳檔案寫到臨時檔案中,然後存放到系統臨時資料夾中。
改變upload handler的行為
三個設定控制django檔案上傳的行為:
file_upload_max_memory_size:直接讀入記憶體的最大上傳檔案大小(位元組數)。當大於此值時,檔案存放到磁碟。預設2.5m位元組
file_upload_temp_dir
file_upload_permissions:許可權
file_upload_handlers
上傳檔案真正的處理器。修改此項設定可以完成自定義django上傳檔案的過程。
預設是:
("django.core.files.uploadhandler.memoryfileuploadhandler",
"django.core.files.uploadhandler.temporaryfileuploadhandler
",)
先嘗試裝入記憶體,如不行就存入到臨時檔案。
上傳檔案封裝方法:
'''檔案上傳
'''def
handle_uploaded_file(f):
file_name = ""
try:
path = "
media/image
" + time.strftime('
/%y/%m/%d/%h/%m/%s/')
ifnot
os.path.exists(path):
os.makedirs(path)
file_name = path +f.name
destination = open(file_name, '
wb+'
)
for chunk in
f.chunks():
destination.write(chunk)
destination.close()
except
exception, e:
e
return file_name
django 檔案上傳
檔案上傳 當django處理上傳乙個檔案的時候,檔案資料被放在request.files中。這個文件解釋檔案怎麼樣被儲存在磁碟上或者記憶體中,怎樣定製預設的行為。基本檔案上傳 考慮乙個包含filefield的簡單的表單 from django import forms class uploadfil...
django 檔案上傳
檔案上傳 當django處理上傳乙個檔案的時候,檔案資料被放在request.files中。這個文件解釋檔案怎麼樣被儲存在磁碟上或者記憶體中,怎樣定製預設的行為。基本檔案上傳 考慮乙個包含filefield的簡單的表單 from django import forms class uploadfil...
Django檔案上傳
lang en charset utf 8 titletitle head action home method post enctype multipart form data type file name file type submit value 提交 p form div body htm...