model
from django.db import models
class Picture(models.Model):
path = models.ImageField(upload_to='share_pictures/')
name = models.CharField(max_length = 50)
class Meta:
db_table = "picture"
def __str__(self):
return self.name
from django import forms
class ImageForm(forms.Form):
name = forms.CharField(max_length = 100, label='名字:')
picture = forms.ImageField(label='图片:')
Views
class PictureView(APIView):
def get(self, request):
name = request.GET.get('name', '')
try:
picture = Picture.objects.get(name=name)
except Picture.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
image = open(picture.path.url[1:], 'rb').read()
return HttpResponse(image, content_type='image/png')
def post(self, request):
MyImageForm = ImageForm(request.POST, request.FILES)
# 检验表单是否通过校验
if MyImageForm.is_valid():
# 构造一个 Profile 实例
picture = Picture()
# 获取name
picture.name = MyImageForm.cleaned_data["name"]
# 获取图片
picture.path = MyImageForm.cleaned_data["picture"]
e = picture.save()
print(e)
else:
return Response(status=403)
return Response(status=200)