方式1:数据库存放图片地址,图片存放在Django项目文件中
1.首先,我们现在models.py文件中定义模型来存放该图片数据,前端传来的数据都会存放在Django项目文件里的images文件夹下
from django.db import models
class Image(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
2.下一步,在settings.py文件里配置媒体文件上传
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
3.在forms.py文件中创建表单
from django import forms
from .models import Image
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['title', 'image']
4.在视图文件里增加两个函数,一个是用来前端给后端传图片流数据,后端进行处理;另一个是后端从数据库中调出图片返还给前端
from django.shortcuts import render, redirect
from .forms import ImageForm
from .models import Image
def upload_image(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('image_list')
else:
form = ImageForm()
return render(request, 'upload_image.html', {'form': form})
def image_list(request):
images = Image.objects.all()
return render(request, 'image_list.html', {'images': images})
5.前端upload_image.html
文件。这里为了体现出主要功能,所以写的有些简陋。
<!DOCTYPE html>
<html>
<head>
<title>上传图片</title>
</head>
<body>
<h1>图片上传</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">确认上传</button>
</form>
</body>
</html>
6.前端image_list.html
文件.
<!DOCTYPE html>
<html>
<head>
<title>图片展示</title>
</head>
<body>
<h1>图片列表</h1>
<ul>
{% for image in images %}
<li>
<h2>{{ image.title }}</h2>
<img src="{{ image.image.url }}" alt="{{ image.title }}" style="width: 200px; height: auto;">
</li>
{% endfor %}
</ul>
</body>
</html>
7.在urls.py文件中完成相关配置
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import upload_image, image_list
urlpatterns = [
path('upload/', upload_image, name='upload_image'),
path('images/', image_list, name='image_list'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
8.最后一步,基础操作,完成创建和应用数据库迁移,运行查看结果
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
方式1流程及效果展示
前后端完整过程为:前端填写图片标题等信息,之后选择图片并传给后端,后端把前端传过来的图片保存在当前项目文件中,并在数据库中存放图片的位置。前端想要查看图片,后端先从数据库中调出图片的位置信息,之后把位置信息传给前端,前端src展示出图片
前端选择并上传图片
后端返还图片
数据库中存放的数据
Django项目文件结构
方式2:数据库直接存放base64转码后的数据,随调随用
1.编写模型,同上
class Base64Image(models.Model):
title = models.CharField(max_length=100)
image_data = models.TextField() # 用于存储base64编码的图片数据
def __str__(self):
return self.title
2.编写表单
class Base64ImageForm(forms.Form):
title = forms.CharField(max_length=100)
image = forms.ImageField()
3.编写视图(在views.imageBase64.py中编写)
import base64
from django.shortcuts import render, redirect
from app01.forms import Base64ImageForm
from app01.models import Base64Image
def upload_base64_image(request):
if request.method == 'POST':
form = Base64ImageForm(request.POST, request.FILES)
if form.is_valid():
title = form.cleaned_data['title']
image = form.cleaned_data['image']
image_data = base64.b64encode(image.read()).decode('utf-8')
Base64Image.objects.create(title=title, image_data=image_data)
return redirect('image_list')
else:
form = Base64ImageForm()
return render(request, 'upload_base64_image.html', {'form': form})
def image_list(request):
images = Base64Image.objects.all()
return render(request, 'image_list.html', {'images': images})
4.前端代码,upload_base64_image.html
<!DOCTYPE html>
<html>
<head>
<title>上传Base64图片</title>
</head>
<body>
<h2>测试上传</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">上传</button>
</form>
</body>
</html>
5.前端代码,image_list.html
<!DOCTYPE html>
<html>
<head>
<title>base64图片张氏</title>
</head>
<body>
<h2>图片列表</h2>
<ul>
{% for image in images %}
<li>
<h3>{{ image.title }}</h3>
<img src="data:image/jpeg;base64,{{ image.image_data }}" alt="{{ image.title }}">
</li>
{% endfor %}
</ul>
</body>
</html>
6.url文件中配置相关路径,同上省略
方式2效果展示
1.前端上传图片
2.前端接收base64图片
数据库中图片数据展示