Django處理檔案上傳File Uploads

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   os   ar   使用   java   

HttpRequest.FILES

表單上傳的檔案Object Storage Service在類字典對象request.FILES中,表單格式需為multipart/form-data

<form enctype="multipart/form-data" method="post" action="/foo/"><input type="file" name="image" />

request.FILES中的鍵來自於表單中的<input type="file" name="" />的name值:

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

編碼

隱藏檔

想將上傳的檔案儲存體在本地時:

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:

# In forms.py...from django import formsclass UploadFileForm(forms.Form):    title = forms.CharField(max_length=50)    file = forms.FileField()

用Form處理:

>>> f =UploadFileFormt(request.POST, request.FILES)

view函數:

from django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom .forms import UploadFileFormdef 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:

from django.db import modelsclass NicEditImage(models.Model):    image = models.ImageField(upload_to=‘nicedit/%Y/%m/%d‘)

建立ModelForm:

from django import formsclass NicEditImageForm(forms.ModelForm):    class Meta:        model = NicEditImage

view:

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的檔案域:

from django.http import HttpResponseRedirectfrom django.shortcuts import renderfrom .forms import UploadFileFormfrom .models import ModelWithFileFielddef 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處理

想獲得更大自由度時,可以全手動處理。

from django.db import modelsclass 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有以下屬性:

>>> car = Car.objects.get(name="57 Chevy")>>> car.photo<ImageFieldFile: chevy.jpg>>>> car.photo.nameu‘cars/chevy.jpg‘>>> car.photo.pathu‘/media/cars/chevy.jpg‘>>> car.photo.urlu‘http://media.example.com/cars/chevy.jpg‘

Model的FileField是一個File對象,除了具有File對象的各種方法外,還有一個額外的save()方法:

FieldFile.save(name, content, save=True)

 name為儲存名字,content為File或者File子類的執行個體

>>> car.photo.save(‘myphoto.jpg‘, content, save=False)>>> car.save()

類似於

>>> car.photo.save(‘myphoto.jpg‘, content, save=True)

手動儲存:

from django.core.files.base import ContentFilephoto=request.FILES.get(‘photo‘,‘‘)if photo:       file_content = ContentFile(photo.read())   #建立File對象    car.photo.save(photo.name, file_content)   #儲存檔案到car的photo域    car.save()

  

  

 

 

 

 

Django處理檔案上傳File Uploads

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.