首页 > 解决方案 > Python PIL 在 Django TemporaryUploadedFile 上失败

问题描述

我有一个允许摄影师上传文件的成像工具。上传后,我想检查上传的图像是否确实是有效的 JPEG 文件。

所以我写了以下验证函数:

    def validate_JPG(self, image):
    ''' JPEG validation check. '''
    # Since PIL offers a more rubust check to validate if the image
    # is an JPEG this is used instead of checking the file header.
    try:
        img = Image.open(image)
        if img.format != 'JPEG':
            raise JPEGValidationFailed()
        else:
            return True
    except IOError, e:
        self.logger.debug('Error in the JPG validation: {}'.format(e))
        return False

从获取图像的上传视图调用该函数:

    uploaded_file = self.request.FILES.get('image_file')

    image_checksum = sha256(uploaded_file.read()).hexdigest()

    if Photos.objects.filter(image_checksum=image_checksum).exists():
        return Response({
            'uploadError': 'Image already exists.'
            }, status=status.HTTP_409_CONFLICT,)
    try:
        self.logger.debug('Parsing: IPTC and EXIF')
        exif, iptc = self.data_parser.process_file(uploaded_file)
    except JPEGValidationFailed, e:
        raise serializers.ValidationError({
            'uploadError': str(e)
            })

    except Exception, e:
        self.logger.error('Error in parsing the IPTC and EXIF data: {}'.format(e))
        raise serializers.ValidationError({
            'uploadError': 'Something has gone wrong.'
            })

这段代码一直运行得很愉快,但现在不知何故失败了。使用了 Pillow 库,Pillow==3.0.0但更新到最新版本也不起作用。

遇到以下错误:

cannot identify image file <TemporaryUploadedFile: YV180707_7856.jpg (image/jpeg)>

image.seek(0)也行不通。

有人能帮我吗?

标签: pythonpython-imaging-librarypillow

解决方案


好的......所以在休息并再次查看代码后,我注意到在将文件传递到视图之前使用相同的上传文件写入文件(备份保存):

  file.write(image_file.read())

所以该文件已经被读取过一次。在将它传递给视图image_file.seek(0) 之前,我必须先放一个……这就是解决方法。希望它最终对某人有所帮助。


推荐阅读