Django框架實現圖片上傳,存儲和顯示功能

在django框架中,前端頁面不能直接使用相對路徑或絕對路徑顯示圖片,需要通過urls.py來提供每個URL 對應的django的函數來顯示在頁面 。
思路:將form表單上傳的文件,後臺接受後創建文件夾接受並存儲到數據庫中,我的圖片路徑存儲在D:\workspace\upload_pic\media,然後新建一個文件存放在裏邊,上傳成功後返回圖像
新建一個數據表
model.py

from django.db import models
class imginfo(models.Model):
    img = models.FileField(upload_to='media')

urls.py

from django.contrib import admin
from django.urls import path, re_path
from app01 import views
from django.views.static import serve  #圖片顯示
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    re_path('media/(?P<path>.*)$', serve, {'document_root': r'D:\workspace\upload_pic\media'}),
    #這句意思是將訪問的圖片href由“http://127.0.0.1:8888/media/圖片存儲文件夾/字母哥.jpg”轉爲本地訪問D:\workspace\upload_pic\media的形式
    path('login/', views.login),
]

在setting.py 裏邊添加以下代碼,爲了創建文件

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, 'media').replace('\\', '/'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

views.py的代碼

from django.shortcuts import render, HttpResponse
from django.conf import settings       #導入settings
import os                   #創建文件夾需要的包
from app01 import models


# Create your views here.

#
def index(request):
    if request.method == 'POST':
        img = request.FILES.get('img')
        path = settings.MEDIA_ROOT      
        file = '圖片存儲文件夾'
        pic_path = path + '/' + file
        print(pic_path)
        isExists = os.path.exists(pic_path)  			# 路徑存在則返回true,不存在則返回false
        if isExists:
            print("目錄已存在")
        else:
            os.mkdir(pic_path) 
            print("創建成功")
        img_url = pic_path + '/' + img.name
        print(img_url)
        with open(img_url, 'wb') as f:                #將圖片以二進制的形式寫入
            for data in img.chunks():
                f.write(data)
        pic_data = 'http://127.0.0.1:8888/media' + '/' + 'file' + img.name       
        #將路徑轉化一下,轉爲href的形式,然後存入數據庫,發到後端
        models.imginfo.objects.create(img=pic_data)                     #生成一條數據
        img_href = models.imginfo.objects.filter(id=1)[0]
        #將id爲1的數據取出
        print(img_href)
        return render(request, 'login.html', {'img_href': img_href})
    return render(request, 'index.html')


def login(request):
        return render(request, 'login.html')

index.html

<h1>圖片上傳頁面</h1>
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p><input type="file" name="img" /></p>
    <p><input type="submit" value="提交"></p>
</form>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章