HttpRequest.FILES
表單上傳的文件對象存儲在類字典對象request.FILES中,表單格式需為multipart/form-data
1
2
|
<form enctype=
"multipart/form-data"
method=
"post"
action=
"/foo/"
>
<input type=
"file"
name=
"image"
/>
|
request.FILES中的鍵來自於表單中的<input type="file" name="" />的name值:
1
|
img=request.FILES[
'image'
]
|
request.FILES中的值均為UploadedFile類文件對象。
UploadedFile
UploadedFile是類文件對象,具有以下方法和屬性:
UploadedFile.read()
讀取整個上傳文件的數據,文件較大時慎用。
UploadedFile.multiple_chunks(chunk_size=None)
判斷文件是否足夠大,一般為2.5M
UploadedFile.chunks(chunk_size=None)
返回一個生成器對象,當multiple_chunks()為True時應該使用這個方法來代替read().
UploadedFile.name
上傳文件的name。
UploadedFile.size
上傳文件的大小。
UploadedFile.content_type
上傳文件時的content_type報頭,例如(e.g. text/plain or application/pdf).
UpladedFile.charset
編碼
存儲文件
想將上傳的文件存儲在本地時:
1
2
3
4
|
f=request.FILES[
'image'
]
with
open(
'some/file/name.txt'
,
'wb+'
) as destination:
for
chunk
in
f.chunks():
destination.write(chunk)
|
使用Form處理上傳文件
也可以使用django自帶的form來處理上傳文件。
先創建帶FileFiled或者ImageFiled的Form:
1
2
3
4
5
6
|
# In forms.py...
from django
import
forms
class
UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
|
用Form處理:
1
|
>>> f =UploadFileFormt(request.POST, request.FILES)
|
view函數:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from django.http
import
HttpResponseRedirect
from django.shortcuts
import
render_to_response
from .forms
import
UploadFileForm
def handle_uploaded_file(f):
with
open(
'some/file/name.txt'
,
'wb+'
) as destination:
for
chunk
in
f.chunks():
destination.write(chunk)
def upload_file(request):
if
request.method ==
'POST'
:
form = UploadFileForm(request.POST, request.FILES)
if
form.is_valid():
handle_uploaded_file(request.FILES[
'file'
])
return
HttpResponseRedirect(
'/success/url/'
)
else
:
form = UploadFileForm()
return
render_to_response(
'upload.html'
, {
'form'
: form})
|
使用Model處理上傳文件
如果創建了一個帶FileField或者ImageField域的Model,需要將上傳文件存儲到Model的FileFIeld域。
比如,使用nicEdit文本編輯器時,需要存儲上傳的文件,建立Model:
1
2
3
4
|
from django.db
import
models
class
NicEditImage(models.Model):
image = models.ImageField(upload_to=
'nicedit/%Y/%m/%d'
)
|
創建ModelForm:
1
2
3
4
5
|
from django
import
forms
class
NicEditImageForm(forms.ModelForm):
class
Meta:
model = NicEditImage
|
view:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
def upload(request):
if
not request.user.is_authenticated():
json = simplejson.dumps({
'success'
: False,
'errors'
: {
'__all__'
:
'Authentication required'
}})
return
HttpResponse(json, mimetype=
'application/json'
)
form = NicEditImageForm(request.POST or None, request.FILES or None)
if
form.is_valid():
image = form.save()
#保存Form和Model
json = simplejson.dumps({
'success'
: True,
'upload'
: {
'links'
: {
'original'
: image.image.url},
'image'
: {
'width'
: image.image.width,
'height'
: image.image.height}
}
})
else
:
json = simplejson.dumps({
'success'
: False,
'errors'
: form.errors})
return
HttpResponse(json, mimetype=
'application/json'
)
|
當然也可以手動存儲文件到Model的文件域:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from django.http
import
HttpResponseRedirect
from django.shortcuts
import
render
from .forms
import
UploadFileForm
from .models
import
ModelWithFileField
def upload_file(request):
if
request.method ==
'POST'
:
form = UploadFileForm(request.POST, request.FILES)
if
form.is_valid():
instance = ModelWithFileField(file_field=request.FILES[
'file'
])
#保存文件到FileField域
instance.save()
return
HttpResponseRedirect(
'/success/url/'
)
else
:
form = UploadFileForm()
return
render(request,
'upload.html'
, {
'form'
: form})
|
不使用Form處理
想獲得更大自由度時,可以全手動處理。
1
2
3
4
5
6
|
from django.db
import
models
class
Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to=
'cars'
)
|
Model的FileField有以下屬性:
1
2
3
4
5
6
7
8
9
|
>>> car = Car.objects.get(name=
"57 Chevy"
)
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
u
'cars/chevy.jpg'
>>> car.photo.path
u
'/media/cars/chevy.jpg'
>>> car.photo.url
u
'http://media.example.com/cars/chevy.jpg'
|
Model的FileField是一個File對象,除了具有File對象的各種方法外,還有一個額外的save()方法:
FieldFile.save(name, content, save=True)
name為存儲名字,content為File或者File子類的實例
1
2
|
>>> car.photo.save(
'myphoto.jpg'
, content, save=False)
>>> car.save()
|
類似於
1
|
>>> car.photo.save(
'myphoto.jpg'
, content, save=True)
|
手動存儲:
1
2
3
4
5
6
|
from django.core.files.base
import
ContentFile
photo=request.FILES.get(
'photo'
,
''
)
if
photo:
file_content = ContentFile(photo.read())
#創建File對象
car.photo.save(photo.name, file_content)
#保存文件到car的photo域
car.save()
|