16 檔案上傳meidia路徑的配置和使用

2022-05-02 23:12:10 字數 2491 閱讀 7207

目錄在專案 /static/ 靜態資料夾中新建media資料夾 # 當然也可以放在專案根目錄下,看專案需求

在檔案上傳後會被儲存到/static/media/檔案

示例**如下:

# 1. settings.py 檔案

# 靜態檔案路徑設定

static_url = '/static/'

staticfiles_dirs = [os.path.join(base_dir, 'static')]

# 檔案上傳路徑設定

media_root = os.path.join(base_dir, 'static/media')

# 2. 上傳檔案

# 模板檔案如下, uploadfile.html# 檢視, 這裡使用類檢視

from datetime import datetime

from 專案名.settings import media_root

import os

from django.views import view

class uploadfile(view):

def get(self, request):

"""get 請求走這裡, 渲染乙個模板"""

return render(request, 'upload_file_test/uploadfile.html')

def post(self, request):

"""post 請求 走這個方法"""

file_1 = request.files.get('file_1', none)

if file_1: # 有檔案的時候

""" # 直接上傳到 media 目錄下

file_name = os.path.join(base_dir, file_1.name)

with open(file_name, 'wb') as f:

for i in file_1.chunks():

f.write(i)

return httpresponse('檔案上傳成功')

"""# 2. 把每天上傳的檔案按照日期放在不同的目錄下

upload_time = datetime.now().strftime('%y%m%d')

upload_time_dir = os.path.join(media_root, upload_time)

if not os.path.exists(upload_time_dir): # 如果檔案目錄不存在, 則建立

os.mkdir(upload_time_dir)

file_name = os.path.join(upload_time_dir, file_1.name)

with open(file_name, 'wb') as f:

for i in file_1.chunks():

f.write(i)

return httpresponse('沒有選擇檔案')

# 同時上傳多個檔案, 用函式方式實現, 類檢視與函式檢視都是差不多的

def upload_files(request):

if request.method == 'post':

files = request.files.getlist('files', none)

if files:

for file in files:

upload_time = datetime.now().strftime('%y%m%d') # 上傳時間

upload_time_dir = os.path.join(media_root, upload_time) # 拼接路徑

if not os.path.exists(upload_time_dir): # 如果沒有這個目錄

os.mkdir(upload_time_dir)

file_name = os.path.join(upload_time_dir, file.name)

with open(file_name, 'wb') as f:

for line in file.chunks(): # 讓檔案以檔案流的形式 寫入

f.write(line)

return httpresponse('檔案上傳成功')

return httpresponse('沒有選擇檔案')

return render(request, 'upload_file_test/uploadfile.html')

類檢視實現的單檔案上傳

使用函式方式實現的多檔案上傳

html 模板

1 6 檔案上傳元件

1.6 檔案上傳元件 1.6.1 基本形制 form的完整形制如下,它必須設定enctype multipart form data 才能進行檔案提交。1.6.2 常用屬性 1.6.2.1 型別type type file 說明這個控制項是乙個檔案上傳元件,由乙個文字框和乙個按鈕組合而成。1.6.2...

springboot系列16 檔案上傳

檔案上傳用到的場景也比較多,如頭像的修改 相簿應用 附件的管理等等,今天就來學習下在springboot框架下應用檔案上傳技術。org.springframework.boot spring boot starter web org.springframework.boot spring boot ...

90 檔案上傳

1 檔案上傳 首先設定請求體 使用乙個nsmutabledata進行資料拼接 本次上傳標示字串 r ncontent disposition form data name 服務端字段 filename 上傳檔名 r ncontent type 上傳檔案mimetype r n r n要上傳的二進位制...