Django9 2 請求與響應(2) 檔案上傳

2021-10-16 19:12:47 字數 3198 閱讀 9277

本文接上文

一般的檔案路徑,我們會放在static中,建立乙個media資料夾。

配置:在settings最後新增:

media_root = os.path.join(base_dir,

'static/media'

)

建立fileup.html檔案

lang

="en"

>

>

charset

="utf-8"

>

>

檔案上傳title

>

head

>

>

method

="post"

enctype

="multipart/form-data"

>

type

="file"

name

="file"

>

type

="submit"

value

="submit"

>

form

>

body

>

html

>

注意:一定要加許可權認證和enctype

配置路由:

# -*- coding: utf-8 -*-

# @author : summer

from django.urls import path

from

.import views

"students"

urlpatterns =

[ path(

"login"

, views.login, name=

"login"),

# 使用者登入測試

path(

"", views.fileup, name=

'fileup'),

# 檔案上傳測試

)# 獲取檔案

file_name =

file

.name # 檔名

# 將每天的檔案放到每天的資料夾

day_dir = datetime.now(

).strftime(

"%y%m%d"

) dir_path = os.path.join(media_root, day_dir)

ifnot os.path.exists(dir_path)

:# 檢視資料夾是否存在,如果不存在則建立

os.mkdir(dir_path)

file_path = os.path.join(dir_path, file_name)

# 將檔名拼接到medai路徑

with

open

(file_path,

'wb'

)as f:

for line in

file

.chunks():

# 上傳檔案過大時,將檔案自動分塊

f.write(line)

return render(request,

'student/fileup.html'

)

前端需要修改file內容

type

="file"

name

="file"

multiple

>

後台:

def

fileup

(request)

:if request.method ==

"post"

:# file = request.files.get('file') # 獲取乙個檔案

files = request.files.getlist(

'file'

)# 獲取多個檔案

# 將每天的檔案放到每天的資料夾

day_dir = datetime.now(

).strftime(

"%y%m%d"

) dir_path = os.path.join(media_root, day_dir)

ifnot os.path.exists(dir_path)

:# 檢視資料夾是否存在,如果不存在則建立

os.mkdir(dir_path)

# 新增一張

# file_path = os.path.join(dir_path, file.name) # 將檔名拼接到medai路徑

# with open(file_path, 'wb') as f:

# for line in file.chunks(): # 上傳檔案過大時,將檔案自動分塊

# f.write(line)

# 新增多張

forfile

in files:

file_path = os.path.join(dir_path,

file

.name)

# 將檔名拼接到medai路徑

with

open

(file_path,

'wb'

)as f:

for line in

file

.chunks():

# 上傳檔案過大時,將檔案自動分塊

f.write(line)

return render(request,

'student/fileup.html'

)

Django中請求與響應

利用http的幾種傳參路徑 1 url路徑引數 return httpresponse ok 2 django中的querydict物件 httprequest物件的屬性get post都是querydict型別的物件 qs a 1 b 2 a 3 def qs request a request....

django 9 請求與響應

寫在表單下面 檔案上傳 settings.py upload root os.paht.join base dir,upload enctype multipart form data 上傳多個檔案 multiple request用於接受前端的資料 render用於給前端返回資料 file.chu...

Django2 0 請求與響應(下)

上篇講完了請求,這篇接著講下響應,django響應型別大致有以下幾種 使用django.http.httpresponse來構造響應物件,可利用httpresponse這個類來進行響應的例項化。httpresponse content 響應體,content type 響應體資料型別,status ...