python - 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)
也行不通。
有人能帮我吗?
解决方案
好的......所以在休息并再次查看代码后,我注意到在将文件传递到视图之前使用相同的上传文件写入文件(备份保存):
file.write(image_file.read())
所以该文件已经被读取过一次。在将它传递给视图image_file.seek(0)
之前,我必须先放一个……这就是解决方法。希望它最终对某人有所帮助。
推荐阅读
- r - 在 R 中写入和读取 csv 文件的问题
- azure-devops - Azure DevOps - 清理构建目录
- python-3.x - 从 Numpy 数组中获取变量
- angular - 这是否可以根据用户是否经过身份验证在同一路线上使用多个布局?
- c - 为什么 Ken Thompson 在“对信任的反思”中提到的 C 语言中的这种 quine 不起作用?
- javascript - OJET - 我如何在离开我的页面之前提醒用户?
- reactjs - 在 React 中的函数组件之外声明函数
- c# - 在 C# 中获取调用堆栈
- python - 使用 LSTM 进行多变量多步时间序列预测
- vuefire - VueFire:如何将 this.$bind('photos') 移动到组件的全局范围?