【问题标题】:How to convert Bytes object to _io.BytesIO python?如何将 Bytes 对象转换为 _io.BytesIO python?
【发布时间】:2020-09-21 12:39:13
【问题描述】:

我正在制作一个简单的 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)

有人可以帮忙吗???

【问题讨论】:

    标签: python api flask


    【解决方案1】:

    您似乎很困惑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'
    

    这应该让您了解readBytesIO 上的工作原理。我想你需要做的是这个。

    return send_file(
        BytesIO(image.data),
        mimetype='image/jpg',
        as_attachment=True,
        attachment_filename='f.jpg'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 2022-07-26
      • 1970-01-01
      • 2014-08-03
      • 2010-09-29
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      相关资源
      最近更新 更多