django實現分區上傳檔案

來源:互聯網
上載者:User

標籤:file   chunk   val   text   ima   mit   post   body   har   

目標:利用django實現上傳檔案功能

1,先設定路由系統

urls.py

from django.conf.urls import url,includefrom django.contrib import adminfrom app01 import viewsurlpatterns = [    url(r‘^admin/‘, admin.site.urls),    url(r‘^upload/$‘, views.upload),]

 

2,配置html模板檔案(前端頁面展示)

templates/upload.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><form action="/upload/" method="post" enctype="multipart/form-data">    <p><input type="file" name="f1"></p>    <p><input type="text" name="hostname"></p>    <input type="submit" value="upload"></form></body></html>

 

3,開始寫上傳邏輯

views.py


#_*_ coding:utf-8 -*-
from django.shortcuts import render,HttpResponse
from django.views.generic.list import ListView

def index(request):
return HttpResponse("haha")

def upload(request):
if request.method == "POST": #判斷接收的值是否為POST
inp_files = request.FILES #上傳檔案的接收方式應該是request.FILES
file_obj = inp_files.get(‘f1‘) #通過get方法擷取upload.html頁面提交過來的檔案
f = open(file_obj.name,‘wb‘) #將用戶端上傳的檔案儲存在伺服器上,一定要用wb二進位方式寫入,否則檔案會亂碼
for line in file_obj.chunks(): #通過chunks分區上傳儲存在伺服器記憶體中,以64k為一組,迴圈寫入到伺服器中
f.write(line)
f.close()

return render(request,‘upload.html‘) #將處理好的結果通過render方式傳給upload.html進行渲染

 

 

4,上傳功能全部完成,比較簡單,我們來進行驗證

上傳本地一個png的圖片,然後點擊upload提交

 

點擊提交後,在伺服器上看到了剛剛上傳的檔案“django流程圖”

 

通過Django實現分區上傳檔案成功。

 

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.