(轉)django上傳檔案

來源:互聯網
上載者:User

標籤:

本文轉自:http://www.cnblogs.com/linjiqin/p/3731751.html

emplate 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 import formsclass UploadFileForm(forms.Form):    title = forms.CharField(max_length=50)    file = forms.FileField()

處理這個form的視圖收到了在request.FILES中的檔案資料。從上述form來的資料可以通過request.FILES[‘file‘]來存取。
特別注意的是:

  只有當request方法是POST

  且發送request的<form>有屬性enctype="multipart/form-data"時,request.FILES中包含檔案資料,否則request.FILES為空白。

以下視圖函數:

from django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom somewhere import handle_uploader_filedef 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})

必須要將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函數

def handle_uploaded_file(f):    destination = open(‘some/file/name.txt‘, ‘wb+‘)    for chunk in f.chunks():        destination.write(chunk)    destination.close()

詳細點:

def handle_uploaded_file(f):    file_name = ""    try:        path = "media/editor" + time.strftime(‘/%Y/%m/%d/%H/%M/%S/‘)        if not 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:        print 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/‘)        if not 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:        print e    return file_name

(轉)django上傳檔案

聯繫我們

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