django上傳文件


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 import forms

class 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 HttpResponseRedirect
from django.shortcuts import render_to_response
from somewhere import handle_uploader_file

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})

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM