我有一个成像工具,允许摄影师上传文件。上传后,我想检查上传的图像是否确实是有效的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
该函数从获取图像的upload视图中调用:
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)
也不起作用。
有人能帮我吗?
发布于 2018-07-27 04:44:28
好吧..。因此,在休息一下并再次检查代码后,我注意到在将上传的文件传递给视图之前,有一个文件写入了该文件(backup-save):
file.write(image_file.read())
所以这个文件已经读过一次了。在将其传递给视图之前,我必须放置一个image_file.seek(0)
……这就是解决之道。希望它最终能帮助到某个人。
https://stackoverflow.com/questions/51546166
复制相似问题