如何在restful API中为ImageField发送角度为2的图像?

时间:2017-05-21 10:47:46

标签: python django angular django-rest-framework typescript2.0

最近我正在努力从角度2上传图像并将其保存在django中。为此,我已经制作了宁静的django API。该API正在工作并将文件上传到文件夹中,并在属性中保存图像路径。

现在,我感到困惑的是,我应该以哪种格式将图像发送到django。就像我从角度2中选择文件并在base64中转换它。但它不起作用。这是我的档案。

Model.py

from django.db import models
from time import time


def get_name(instance,filename):
    return "uploaded_files/%s_%s"%(str(time()).replace('.','_'),filename)

# Create your models here.
class Mobile(models.Model):

    SNR_Name= models.CharField(max_length=20)
    SNR_Model= models.CharField(max_length=20)
    SNR_RAM= models.CharField(max_length=20)
    SNR_InternalMemory= models.CharField(max_length=20)
    SNR_CompleteName= models.CharField(max_length=200, default="---")
    SNR_ScreenSize= models.CharField(max_length=20)
    SNR_ExternalMemory= models.CharField(max_length=20)
    SNR_ProcessorSpeed= models.CharField(max_length=20)
    SNR_Other= models.CharField(max_length=200)
    SNR_Available=models.CharField(max_length=50,default="")

    SNR_Link= models.CharField(max_length=1200,default="http.shopnroar.com")


    SNR_Price =models.DecimalField(max_digits=8,decimal_places=2,default=00)
    SNR_date = models.DateTimeField(auto_now_add=True, blank=True)
    SNR_Thumbnail=models.FileField(upload_to=get_name, blank=True)
    class Meta:
        unique_together = (('SNR_Name', 'SNR_Model','SNR_RAM','SNR_Link'),)

    def __str__(self):
        return self.SNR_Name+' , '+self.SNR_Model+' , '+self.SNR_RAM+' , '+self.SNR_ProcessorSpeed+' , '+self.SNR_InternalMemory+' , '+self.SNR_ExternalMemory+','+self.SNR_CompleteName+' , '+self.SNR_ScreenSize+' , '+str(self.SNR_Price)+' , '+self.SNR_Other+','+self.SNR_Available+' , '+self.SNR_Link+' , '+str(self.SNR_Thumbnail)

Serilizer.py

    from rest_framework import serializers

from .models import Mobile

class Mobile_Serializer(serializers.ModelSerializer):

    class Meta:
        model=Mobile
        fields=('SNR_Name','SNR_Model','SNR_RAM','SNR_ProcessorSpeed' , 'SNR_InternalMemory','SNR_ExternalMemory','SNR_CompleteName','SNR_ScreenSize','SNR_Price','SNR_Other','SNR_Available','SNR_Link','SNR_Thumbnail')

和我的 view.py

def add_Mobiles(request):

    if request.method == 'POST':

        serializer = Mobile_Serializer(data=request.data)


        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)

当我运行它时抛出django admin,它上传图像。 但它在我的API中将如何运作。我在SNR_Thumbnail中发送base64图像,但它给了我错误。 任何人都可以解决这个问题吗?从角度2我怎样才能在django或任何其他黑客中发送图像。 我将非常感谢这一点。

1 个答案:

答案 0 :(得分:0)

您应该在序列化程序中使用Base64ImageField。您必须安装drf-extra-fields才能使用它。 然后,在Mobile_Serializer

class Mobile_Serializer(serializers.ModelSerializer):
     image = Base64ImageField(required=False)
     .....................