Django(十九)文件上傳:圖片上傳(后台上傳、自定義上傳)、


一、基本設置

參考:https://docs.djangoproject.com/zh-hans/3.0/topics/http/file-uploads/

1)配置project1/settings.py

因為圖片也屬於靜態文件,所以保存到static目錄下。

MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")

2)在static目錄下創建media目錄,再創建應用名稱的目錄,此例為app1

F:\Test\django-demo\project1>tree /f
F:.
│  db.sqlite3
│  manage.py
│
├─app1
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  urls.py
│  │  views.py
│  │  __init__.py
│  │
│  ├─migrations
│  │  │  __init__.py
│  │  │
│  │  └─__pycache__
│  │          __init__.cpython-37.pyc
│  └─
│
├─project1
│  │  asgi.py
│  │  settings.py
│  │  urls.py
│  │  wsgi.py
│  │  __init__.py
│  │
│  └─
│
├─static
│  ├─css
│  ├─images
│  ├─js
│  └─media
│      └─app1
└─templates
    └─app1
            index.html

二、上傳圖片

模型知識回顧:

在七章https://blog.csdn.net/u010132177/article/details/103855700

字段類型里有兩個類型:

  1. FileField:上傳文件字段。
  2. ImageField:繼承於FileField,對上傳的內容進行校驗,確保是有效的圖片。

准備工作:

1)執行遷移

python manage.py makemigrations

2)執行遷移(如果第1次不執行則3提示不存在auth表)

python manage.py migrate

3)創建管理員用戶

python manage.py createsuperuser

4)如果第2次執行遷移提示沒有更改項

可修改migrations文件夾下的0001_initial.py文件名,或刪除數據庫里的migrations表的對應0001_initial那條

5)相關詳細操作見全棧視頻10圖片上傳第1節

6)在python中進行圖片操作,需要安裝包PIL。

pip install Pillow==3.4.1

1. 后台管理admin頁面上傳

0)創建包含圖片的模型類

將模型類的屬性定義成models.ImageField類型。

1)打開app1/models.py文件,定義模型類PicTest。

class PicTest(models.Model):
    pic = models.ImageField(upload_to='booktest/')

2)回到命令行中,生成遷移。

python manage.py makemigrations

3)打開booktest/migrations/0001_initial.py文件,刪除AreaInfo部分,因為這個表已經存在。

在這里插入圖片描述

4)回到命令行中,執行遷移。

python manage.py migrate

如果之前有操作過圖書類、英雄類模型創建過數據表,又因為當前沒有定義圖書、英雄模型類,會提示“是否刪除”,輸入“no”后回車,表示不刪除。

5)注冊1步寫的模型類

from django.contrib import admin
from app1.models import PicTest # 【1】導入app1目錄下的models文件內的PicTest模型類

# Register your models here.

admin.site.register(PicTest) # 【2】注冊模型類

6)運行項目登錄后台:http://127.0.0.1:8000/admin

運行項目:

py manage.py runserver
  • 依次點進去即可看到上傳圖片按鍵:首頁 › App1 › Pic tests › 增加 pic test
  • 上傳一個圖片即可在static/media/app1下看到剛上傳的圖片
  • 如果上傳非有效圖片,系統會自動幫檢測,並給出提示

2.自定義上傳頁面

1)創建模板templates/upload_pic.html

【1】圖片上傳必須要設置enctype="multipart/form-data",后台才能接收到數據
【2】post上傳別忘記帶上驗證標識{% csrf_token %}

<!DOCTYPE html>
<html>
<head>
	<title>自定義圖片上傳</title>
</head>
<body>

	<!-- 【1】圖片上傳必須要設置enctype="multipart/form-data",
	后台才能接收到數據 -->
	<form method='post' enctype="multipart/form-data" action="/upload_handle/">
		{% csrf_token %} {# 【2】post上傳別忘記帶上驗證標識 #}
		<input type="file" name="pic"><br/>
		<input type="submit" value="上傳">
	</form>

</body>
</html>

2)編寫視頻函數app1/views.py

【1-5】
圖上上傳處理,圖片2種類型:

  1. 小於2.5M放在內存中:<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
  2. 大於2.5放在硬盤上:<class 'django.core.files.uploadedfile.TemporaryUploadedFile'>
from django.shortcuts import render
from django.http import HttpResponse
from project1.settings import MEDIA_ROOT #導入上傳文件保存路徑 或 from django.conf import settings
from app1.models import PicTest #導入圖片模型類


# /index
def index(request):
	return render(request,'app1/index.html')


# /show_upload
def show_upload(request):
	'''圖片上傳頁'''
	return render(request,'app1/upload_pic.html')

# /upload_handle
# 圖上上傳處理,圖片2種類型:
# 小於2.5M放在內存中:<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
# 大於2.5放在硬盤上:<class 'django.core.files.uploadedfile.TemporaryUploadedFile'>
def upload_handle(request):
	'''圖片上傳處理頁'''
	#【1】得到圖片
	pic=request.FILES['pic']
	#【2】拼接圖片保存路徑+圖片名
	save_path="%s/app1/%s"%(MEDIA_ROOT,pic.name)
	#【3】保存圖片到指定路徑,因為圖片是2進制式,因此用wb,
	with open(save_path,'wb') as f:
		# pic.chunks()為圖片的一系列數據,它是一一段段的,所以要用for逐個讀取
		for content in pic.chunks():
			f.write(content)

	#【4】保存圖片路徑到數據庫,此處只保存其相對上傳目錄的路徑
	PicTest.objects.create(goods_pic='app1/%s'%pic.name)

	#【5】別忘記返回信息
	return HttpResponse('上傳成功,圖片地址:app1/%s'%pic.name)

3)app1/urls.py配置

"""project1 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app1 import views

urlpatterns = [
    path('index/', views.index),
    
    path('show_upload/',views.show_upload),# 圖片上傳頁
    path('upload_handle/',views.upload_handle),# 圖片上傳處理頁
]

效果:http://127.0.0.1:8000/show_upload/

上傳圖片操作后會返回上傳成功,及圖片地址。
對應目錄下也會多一個剛上傳的圖片。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM