標籤:
django上傳檔案,查詢到的資料都是用的django自己的models.Model類,去定義一個FileField類型的隱藏檔,並且在裡面加一句upload_to,如下所示: 但是如果用mongodb,雖然Document有FileField類型,但是沒有upload_to這個參數,所以寫了一個方法去將POST裡面的檔案儲存體到本地
隱藏檔的方法如下:
def uploaded_file(f,filename):
address =‘C:/Users/XXXX/Desktop/‘+filename
destination = open(address, ‘wb+‘)
for chunk in f.chunks():
destination.write(chunk)
destination.close()
注方法說明:參數f為POST的FILES檔案,filename為要儲存的檔案名稱,之所以沒有用一個固定的地址,是因為上傳的檔案類型是不定的,可能還txt,也可能是jpg等
html模板裡的上傳代碼:
<form id="formid" method="POST" action="" enctype="multipart/form-data">
<div class="file-box">
<input type=‘text‘ name=‘protextfield‘ id=‘protextfield‘ class=‘txt‘ />
<input type=‘button‘ class=‘btn‘ value=‘瀏覽...‘ />
<input type="file" name="proupload" class="file" id="fileField" size="28" onchange="document.getElementById(‘protextfield‘).value=this.value" />
<input type="submit" name="submit" class="btn" value="上傳" />
</div>
</form>
模板注意點:form必須加enctype="multipart/form-data",否則不能傳送檔案。
在view.py裡調用該方法執行的上傳操作
def newproject(request):
if request.FILES:
filename =request.FILES[‘proupload‘].name
uploaded_file(request.FILES[‘proupload‘],filename)
post.proadress = filename
return render_to_response(‘XXX.html‘, locals())
說明:上面的方法中的filename是獲得了上傳的檔案名稱,包括檔案尾碼,例如test.txt。request.FILES[‘proupload‘]是獲得了名字為proupload的檔案。這麼做的結果就是將上傳的檔案儲存體到了一個本地固定的位置,並儲存了檔案名稱到資料庫裡。 其他說明:目前沒有做下載,但是下一步思路是想將所有檔案固定儲存到一個檔案夾裡,或者按尾碼去分開儲存,然後下載的時候按照檔案名稱在隱藏檔夾裡遍曆,取出要找的檔案進行下載。
django MongoDB上傳檔案