上传图片django休息框架已损坏

时间:2017-09-06 17:54:22

标签: python django django-rest-framework

我有下一个上传图片的视图,但生成的图片已损坏。

class FileUploadView(views.APIView):
    parser_classes = (parsers.FileUploadParser,)

    def uploadFile(self, up_file):
        if not os.path.exists(BUILDING_PHOTOS_FOLDER):
            os.mkdir(BUILDING_PHOTOS_FOLDER)
        file_name = '{}.jpeg'.format(uuid.uuid4())

        destination = open(
          '{}/{}'.format(BUILDING_PHOTOS_FOLDER, file_name), 'wb+')
        for chunk in up_file.chunks():
            destination.write(chunk)
            destination.close()

    def put(self, request, filename, format=None):
        file_obj = request.data['file']
        self.uploadFile(file_obj)
        return HttpResponse(status=204)

3 个答案:

答案 0 :(得分:0)

您好,您可以尝试这样

    def uploadFile(self, f):
        filename = f.name
        redington_path = settings.MEDIA_ROOT + '/yourpath/'
        if not os.path.exists(redington_path):
            os.makedirs(redington_path)
        BASE_PATH = settings.MEDIA_ROOT + '/yourpath/'
        os.mkdir(os.path.join(BASE_PATH, vendorid))
        with open(BASE_PATH  + filename, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)

您需要从 request.FILES ['file']

获取文件
    def put(self, request, filename, format=None):
        file_obj = request.FILES['file']
        self.uploadFile(file_obj)
        return HttpResponse(status=204)

答案 1 :(得分:0)

需要添加集G0 X95.090 Y104.910 F4500,而file_name应为format=jpeg     class FileUploadView(views.APIView):         parser_classes =(parsers.FileUploadParser,)

up_file.name

答案 2 :(得分:0)

最后,我解决了从前端发送图像为原始二进制文件的问题。