Django學習筆記(六)Django上傳檔案

來源:互聯網
上載者:User

這個應該是Django的最後一個學習模組了。再深入的就需要到項目裡面去實踐了

Django上傳檔案有兩種方式,一種是傳統的基於IO流的操作,一種是封裝為基於對象的操作。

但是無論哪種操作,都需要先建立上傳檔案的目錄,


一、基於IO流的操作

urls中的配置,基於學習筆記(五)中的表單的提交的blog/param/(?P<id>\d{2})

修改的post方法如下:

def post(req):    if req.method == 'POST':        form = UserForm(req.POST,req.FILES)        if form.is_valid():            print form.cleaned_data            print form.cleaned_data['name']            print form.cleaned_data['userImag'].name            print form.cleaned_data['userImag'].size            #way 1            s = form.cleaned_data['userImag'].read()            fb = file('./djangotest/upload/'+form.cleaned_data['userImag'].name,'wb')            fb.write(s)            fb.close()                        return HttpResponse('OK')        else :            return HttpResponse('Failed')    else :        form =  UserForm()                return render_to_response('param.html',{'form':form})

對應的param.html如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>{{id}}</title></head><body>{{num}}<br/>{{url}}<br/>提交form需要注釋掉settings檔案中MIDDLEWARE_CLASSES的驗證(token驗證)<form action="/blog/post/" method="post" enctype="multipart/form-data"><span style="white-space:pre"></span>{{form.as_p}}<span style="white-space:pre"></span><button type="submit">提交</button></form></body></html>

二、基於對象方式儲存:

首先,配置settings檔案中的

MEDIA_ROOT = './djangotest/'
目的是讓之後的上傳操作的路徑都相對於項目本身的路徑,而不必寫死


增加新的models:

class Files(models.Model):    name = models.CharField(max_length=300)    f = models.FileField(upload_to='upload/')    def __unicode__(self):        return self.name
同步資料庫

修改post方法:

def post(req):    if req.method == 'POST':        form = UserForm(req.POST,req.FILES)        if form.is_valid():            print form.cleaned_data            print form.cleaned_data['name']            print form.cleaned_data['userImag'].name            print form.cleaned_data['userImag'].size            #way 1            s = form.cleaned_data['userImag'].read()            fb = file('./djangotest/upload/'+form.cleaned_data['userImag'].name,'wb')            fb.write(s)            fb.close()                        #way2            f = Files(name=form.cleaned_data['userImag'].name,f=form.cleaned_data['userImag'])            f.save()            return HttpResponse('OK')        else :            return HttpResponse('Failed')    else :        form =  UserForm()                return render_to_response('param.html',{'form':form})


對應的param.html如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>{{id}}</title></head><body>{{num}}<br/>{{url}}<br/>提交form需要注釋掉settings檔案中MIDDLEWARE_CLASSES的驗證(token驗證)<form action="/blog/post/" method="post" enctype="multipart/form-data"><span style="white-space:pre"></span>{{form.as_p}}<span style="white-space:pre"></span><button type="submit">提交</button></form></body></html>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.