1. 程式人生 > >2019.03.23 文件的上傳下載

2019.03.23 文件的上傳下載

quest .get tip index shortcut and nbsp als media

上傳的幾個註意點,post 必須寫enctype = “multipart/form-data 什麽文件編碼的東西

主要是上傳文件插入到數據庫,存放的位置吧,會在本地保存的

主要還是要設置setting input type==file 獲取請求參數的時候用request.FILES.get()

STATIC_URL = ‘/static/‘

MEDIA_URL = ‘/media/‘
MEDIA_ROOT = os.path.join(BASE_DIR,‘media‘)

#global_settings


文件上傳

實現步驟

配置URL

from django.conf.urls import url, include
from django.contrib import admin
?
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^student/‘, include(‘student.urls‘)),
]
?
?

#coding=utf-8
?
from django.conf.urls import url
from . import views
?
urlpatterns=[
url(r‘^$‘, views.Index.as_view()),
?
]
?

創建視圖


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
?
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
?
# Create your views here.
?
?
?
from django.views import View
class Index(View):
def get(self,request):
return render(request,‘index.html‘)
?
?
def post(self,request):
uname = request.POST.get(‘uname‘,‘‘)
photo = request.FILES.get(‘photo‘,‘‘)
import os
if not os.path.exists(‘static‘):
os.makedirs(‘static‘)
?
?
with open(os.path.join(os.getcwd(),‘static‘,photo.name),‘wb‘) as fw:
#一次性讀取文件
fw.write(photo.read())
?
return HttpResponse(‘上傳成功!‘)
?
?
?
?

創建模板


?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/" method="post" enctype="multipart/form-data">
{% csrf_token %}
用戶名:<input type="text" name="uname"/><br/><br/>
頭&emsp;像:<input type="file" name="photo"/><br/><br/>
&emsp;&emsp;&emsp;&emsp;<input type="submit" value="註冊"/>
?
</form>
?
</body>
</html>
?
?

2019.03.23 文件的上傳下載