前端HTML代碼: html
後端代碼:前端
settings.py文件中的目錄及URL設置:數據庫
1 # 添加在settings.py文件最後 2 # root:上傳的文件存儲在‘media’目錄下,有upload_to的爲下級目錄; 3 # url:可經過‘/media/’連接訪問,如:http://127.0.0.1/media/xxx.txt; 4 5 MEDIA_ROOT = os.path.join(BASE_DIR,'media') 6 MEDIA_URL = '/media/'
urls.py文件:django
1 from django.urls import path 2 from . import views 3 from django.conf.urls.static import static 4 from django.conf import settings 5 6 app_name = 'front' 7 urlpatterns = [ 8 path('',views.IndexView.as_view()) 9 ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
models.py文件:json
1 from django.db import models 2 from django.core import validators 3 4 class Article(models.Model): 5 title = models.CharField(max_length=100) 6 content = models.TextField() 7 # 限制只能上傳TXT格式的文件 8 # upload_to:也可根據當前日期建立目錄; 9 # thumbnail = models.FileField(upload_to="%Y/%m/%d",validators=[validators.FileExtensionValidator(['txt'])]) 10 # 傳圖片格式 11 thumbnail = models.ImageField(upload_to="%Y/%m/%d")
forms.py文件:後端
1 from django import forms 2 from .models import Article 3 4 class ArticleForm(forms.ModelForm): 5 class Meta: 6 model = Article 7 fields = '__all__' 8 error_messages = { 9 # 'thumbnail':{ 10 # 'invalid_extension':'只能上傳TXT格式的文件' 11 # }, 12 'thumbnail':{ 13 'invalid_image':'請輸入正確格式的圖片。' 14 } 15 }
views.py文件:app
1 from django.shortcuts import render 2 from django.http import HttpResponse 3 from django.views.generic import View 4 from .models import Article 5 from .forms import ArticleForm 6 7 8 class IndexView(View): 9 def get(self,request): 10 return render(request,'index.html') 11 12 # 將上傳的文件插入數據庫中; 13 # def post(self,request): 14 # title = request.POST.get('title') 15 # content = request.POST.get('content') 16 # file = request.FILES.get('file') 17 # Article.objects.create(title=title,content=content,file=file) 18 # return HttpResponse('success') 19 20 # request.POST:驗證title與content; 21 # request.FILES:驗證file; 22 def post(self,request): 23 form = ArticleForm(request.POST,request.FILES) 24 if form.is_valid(): 25 form.save() 26 return HttpResponse('success') 27 else: 28 print(form.errors.get_json_data()) 29 return HttpResponse('fail')
index.html文件:post
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="" method="post" enctype="multipart/form-data"> 9 <input type="text" name="title"> 10 <input type="text" name="content"> 11 <input type="file" name="thumbnail"> 12 <input type="submit" value="提交"> 13 </form> 14 </body> 15 </html>