django實現檔案上傳(最簡單的方法)

來源:互聯網
上載者:User

標籤:django 檔案上傳

html頁面代碼:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <form enctype="multipart/form-data" action="/app01/upload/" method="POST">{% csrf_token %}       <input type="file" name="upload" />       <br/>       <input type="submit" value="上傳"/>    </form></body></html>



URL配置:

urlpatterns = [,    url(r‘^upload/$‘, upload),]



views.py配置:

def upload(request):    if request.method == ‘GET‘:        return render(request,‘upload.html‘)    elif request.method == ‘POST‘:        content =request.FILES.get("upload", None)        if not content:            return HttpResponse("沒有上傳內容")        position = os.path.join(‘C:\\Users\\huyuan\\Desktop\\test\\upload‘,content.name)        #擷取上傳檔案的檔案名稱,並將其儲存到指定位置        storage = open(position,‘wb+‘)       #開啟隱藏檔        for chunk in content.chunks():       #分塊寫入檔案            storage.write(chunk)        storage.close()                      #寫入完成後關閉檔案        return HttpResponse("上傳成功")      #返回用戶端資訊    else:        return HttpResponseRedirect("不支援的要求方法")


上傳檔案的常用方法和屬性:

   content.read():從檔案中讀取整個上傳的資料,這個方法只適合小檔案

   content.chunks():按塊寫入檔案,通過for迴圈可以將大檔案按塊寫入到磁碟中

   content.name:擷取檔案名稱,包括尾碼

   content.size:擷取檔案大小


本文出自 “自動化營運” 部落格,請務必保留此出處http://hongchen99.blog.51cto.com/12534281/1954705

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.