zoukankan      html  css  js  c++  java
  • Django上传图片

    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
    
    

    forms

    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)
    
    
  • 相关阅读:
    hadoop
    flume
    IP地址查询
    flinkStreamSQL
    StreamSets
    Algorightm----DynamicProgramming
    google
    vue学习
    使用Webstorm快速启动Vue项目配置
    数据库——关系代数中的除法运算【转】
  • 原文地址:https://www.cnblogs.com/daryl-blog/p/11003044.html
Copyright © 2011-2022 走看看