为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 Bytes 对象转换为 _io.BytesIO python?

如何将 Bytes 对象转换为 _io.BytesIO python?

慕村9548890 2023-08-22 15:21:54
我正在制作一个简单的Flask API来上传图像并执行一些操作,然后将其作为二进制存储在数据库中,然后我想使用 send_file()函数下载它,但是,当我传递像字节这样的图像时,它会给我一个错误:return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_attachment=True) TypeError: descriptor“read”需要“_io.BytesIO”对象,但收到“bytes”我的上传图像的代码如下:@app.route('/upload', methods=['POST'])def upload():    images = request.files.getlist('uploadImages')    n = 0    for image in images:        fileName = image.filename.split('.')[0]        fileFormat = image.filename.split('.')[1]        imageRead = image.read()        img = BytesIO(imageRead)        with graph.as_default():            caption = generate_caption_from_file(img)        newImage = imageDescription(name=fileName, format=fileFormat, description=caption,                                    data=imageRead)        db.session.add(newImage)        db.session.commit()        n = n + 1    return str(n) + ' Image has been saved successfully'我的下载图像的代码:@app.route('/download/<int:id>')def download(id):    image = imageDescription.query.get_or_404(id)    return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_attachment=True)任何人都可以帮忙吗???
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

看来你很困惑io.BytesIO。让我们看一些使用的示例BytesIO。


>>> from io import BytesIO

>>> inp_b = BytesIO(b'Hello World', )

>>> inp_b

<_io.BytesIO object at 0x7ff2a71ecb30>

>>> inp.read() # read the bytes stream for first time

b'Hello World'

>>> inp.read() # now it is positioned at the end so doesn't give anything.

b''

>>> inp.seek(0) # position it back to begin

>>> BytesIO.read(inp) # This is same as above and prints bytes stream

b'Hello World'

>>> inp.seek(0)

>>> inp.read(4) # Just read upto four bytes of stream. 

>>> b'Hell'

read这应该能让您了解on 的工作原理BytesIO。我认为你需要做的是这个。


return send_file(

    BytesIO(image.data),

    mimetype='image/jpg',

    as_attachment=True,

    attachment_filename='f.jpg'

)


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 1658 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信