Django實現(xiàn)前臺上傳并顯示圖片功能
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. 項目設(shè)定
settings.py
#添加
ALLOW_UPLOAD = [’jpg’, ’png’, ’jpeg’]
3.app設(shè)定
urls.py
from django.contrib import adminfrom django.urls import path, register_converter, re_pathfrom . import viewsurlpatterns = [ path(’’, views.index, name=’index’), # 上傳首頁 path(’upload/’, views.upload), # 上傳圖片]
views.py
from django.shortcuts import renderfrom .models import User,Articlefrom django.http import HttpResponsefrom django.conf import settingsfrom datetime import datetimeimport osfrom django.shortcuts import redirect, reverseimport 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) # 創(chuàng)建此路徑 # 要不要改圖片的名字 生成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(): # 相當(dāng)于切片f.write(c) User.objects.create(name=name, avator=path + pic.name) return redirect(’myupload:index’)
Django實現(xiàn)后臺上傳并顯示圖片功能
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問題2. Python使用urlretrieve實現(xiàn)直接遠程下載圖片的示例代碼3. 基于vue 動態(tài)菜單 刷新空白問題的解決4. 完美解決vue 中多個echarts圖表自適應(yīng)的問題5. Android打包篇:Android Studio將代碼打包成jar包教程6. Java使用Tesseract-Ocr識別數(shù)字7. vue實現(xiàn)web在線聊天功能8. Springboot 全局日期格式化處理的實現(xiàn)9. python如何計算圓的面積10. SpringBoot+TestNG單元測試的實現(xiàn)
