3

我正在使用Django 2.xDRF

从我的APIView,我想返回pdfeps二进制数据文件。

class DownloadFile(APIView):
    serializer_class = DownloadFileSerializer
    renderer_classes = (BinaryFileRenderer,)

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        name = serializer.validated_data.get('name')
        data = serializer.validated_data.get('imgdata')

        mimetype = None

        data, mimetype = convert_file_to_pdf_or_eps(data)

        if data and mimetype:

            response = Response(data=data, content_type=mimetype)
            ascii_name = get_ascii_name(name, "QRCode")

            response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(filename.split())

            return response
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST, data='Either data or mime type was missing')

BinaryFileRenderer

from rest_framework.renderers import BaseRenderer


class BinaryFileRenderer(BaseRenderer):
    media_type = 'application/octet-stream'
    format = None
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

这适用于pdf数据,但对于EPS数据,它会给出错误

renderer returned unicode, and did not specify a charset value
4

0 回答 0