如何将图像从Django Rest Api发送到Vue SPA?

时间:2018-11-02 14:33:27

标签: python django django-rest-framework vuejs2

我正在使用后端的DRF REST API开发Vue.js 2.0单页应用程序。我将图像存储在文件系统中,我的一个模型有一个名为“ image”的字段,其中包含图像的地址。

我的模特:

class Board(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=400)
    image = models.FileField(upload_to='boards/')
    safe_for_work = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

视图集:

class BoardViewSet(viewsets.ViewSet):
    serializer_class = BoardSerializer

    def list(self, request,):
        queryset = Board.objects.filter()
        serializer = BoardSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Board.objects.filter()
        board = get_object_or_404(queryset, pk=pk)
        serializer = BoardSerializer(board)
        return Response(serializer.data)

当我从Vue SPA呼叫端点时,我没有得到图像,而只得到了本地URL,例如"/storage/boards/board1.jpg"

如何在Vue页面上访问实际图像?

理想情况下,我想从端点获取所有图像的列表并显示它们。

1 个答案:

答案 0 :(得分:0)

由于这个问题,您必须在服务器(Django Rest)中而不是Vue客户端中进行配置。配置序列化器以显示图像的完整路径:

class BoardSerializer(ModelViewSet)
     image = FileField(source='image')
     class Meta:
        model = Article
        fields = [
            'id',
            'image',
            ...
        ]

不要忘记Viewset中的context: { 'request': request }

def list(self, request,):
        queryset = Board.objects.filter()
        serializer = BoardSerializer(queryset, many=True, context: { 'request': request })
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Board.objects.filter()
        board = get_object_or_404(queryset, pk=pk)
        serializer = BoardSerializer(board, context: { 'request': request })
        return Response(serializer.data)

希望有帮助!