您好,登錄后才能下訂單哦!
小編這次要給大家分享的是用代碼實例詳解Django如何實現前臺上傳并顯示圖片,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
1. 前臺
templates/upload/upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/myupload/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} 名字:<input type="text" name="name"><br> 頭像:<input type="file" name="avator"><br> <input type="submit" value="提交"> </form> </body> </html>
2. 項目設定
settings.py
#添加
ALLOW_UPLOAD = ['jpg', 'png', 'jpeg']
3.app設定
urls.py
from django.contrib import admin from django.urls import path, register_converter, re_path from . import views urlpatterns = [ path('', views.index, name='index'), # 上傳首頁 path('upload/', views.upload), # 上傳圖片 ]
views.py
from django.shortcuts import render from .models import User,Article from django.http import HttpResponse from django.conf import settings from datetime import datetime import os from django.shortcuts import redirect, reverse import hashlib # Create your views here. def index(request): users = User.objects.all() article = Article.objects.all() return render(request, 'myupload/index.html', locals()) def upload(request): if request.method == 'GET': return render(request, 'myupload/upload.html') else: name = request.POST.get('name') pic = request.FILES.get('avator') media_root = settings.MEDIA_ROOT # media allow_upload = settings.ALLOW_UPLOAD # ALLOW_UPLOAD # path = 'upload/{}/{}/{}/'.format(datetime.now().year, datetime.now().month, datetime.now().day) '{:02d}'.format path = 'upload/{}/{}/{}/'.format(datetime.now().year,'{:02d}'.format(datetime.now().month), '{:02d}'.format(datetime.now().day)) full_path = media_root + '/' + path # full_path = 'media/upload/2019/12/20' if not os.path.exists(full_path): # 判斷路徑是否存在 os.makedirs(full_path) # 創建此路徑 # 要不要改圖片的名字 生成hash # 這塊要不要判斷圖片類型 .jpg .png .jpeg # '/../../../myviews/setting.py' print(pic) print(full_path) print(full_path+pic.name) if pic.name.split('.')[-1] not in allow_upload: return HttpResponse('fail') with open(full_path + '/' + pic.name, 'wb') as f: for c in pic.chunks(): # 相當于切片 f.write(c) User.objects.create(name=name, avator=path + pic.name) return redirect('myupload:index')
Django實現后臺上傳并顯示圖片功能
看完這篇關于用代碼實例詳解Django如何實現前臺上傳并顯示圖片的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。