Flask Restplus返回损坏PNG文件问题求助
解决Flask-RESTPlus返回PIL生成图片损坏的问题
这个问题我之前也碰到过,主要是flask_restplus的@api.representation装饰器和Flask的send_file之间的处理逻辑冲突导致的,咱们一步步来解决:
问题原因
@api.representation('image/png')是flask_restplus用来定义自定义响应格式的装饰器,它要求你返回一个符合规范的响应对象;但你直接调用send_file的话,这个装饰器会对返回的内容做额外处理,导致图片的二进制数据被错误修改,最终下载的文件就损坏了。
解决方案1:移除多余的representation装饰器
既然send_file已经能正确处理图片类型的响应,完全不需要额外的@api.representation装饰器,直接去掉它就行:
@api.route('/annotate') class Annotate(Resource): def post(self): file = io.BytesIO() img = Image.new('RGBA', (50, 50), (70, 0, 0, 255)) img.save(file, 'png') file.seek(0) return send_file( file, as_attachment=True, attachment_filename='annotated.png', mimetype='image/png' )
解决方案2:使用representation装饰器正确返回响应
如果你确实需要保留@api.representation(比如要统一处理图片响应),那就要按照装饰器的要求,返回一个Response对象,而不是用send_file:
from flask import Response @api.route('/annotate') class Annotate(Resource): @api.representation('image/png') def post(self): file = io.BytesIO() img = Image.new('RGBA', (50, 50), (70, 0, 0, 255)) img.save(file, 'png') file.seek(0) # 直接返回Response对象,设置好头部和数据 response = Response(file.getvalue(), mimetype='image/png') response.headers.set('Content-Disposition', 'attachment', filename='annotated.png') return response
这两种方法都能解决图片损坏的问题,你可以根据自己的需求选一种就行~
内容的提问来源于stack exchange,提问作者InfoPaste
相关产品推荐
相关产品推荐

