django MongoDB上傳檔案

來源:互聯網
上載者:User

標籤:

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上傳檔案

聯繫我們

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