8

I am making a simple flask API for uploading an image and do some progresses then store it in the data base as binary, then i want to download it by using send_file() function but, when i am passing an image like a bytes it gives me an error:

return send_file(BytesIO.read(image.data), attachment_filename='f.jpg', as_attachment=True) TypeError: descriptor

'read' requires a '_io.BytesIO' object but received a 'bytes'

and My code for upload an image as follow:

@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'

And my code for downloading an image:

@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)

any one can help please???

1 Answer 1

13

It seems you are confused io.BytesIO. Let's look at some examples of using 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'

This should give you an idea of how read on BytesIO works. I think what you need to do is this.

return send_file(
    BytesIO(image.data),
    mimetype='image/jpg',
    as_attachment=True,
    attachment_filename='f.jpg'
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.