1

I am trying send a file object of type BytesIO from flask API to angular frontend.

I am using json.dumps(). File object shouldn't be stored on file system. I am using memory for storing file object. Using io.BytesIO().

return json.dumps({'UserId': username, 'file': file_object}), 201

Typerror: <_io.BytesIO object> is not json searializable
Junior_K27
  • 151
  • 1
  • 9

2 Answers2

2

You can use send_file with a file like object:

import io
from flask import send_file

@app.route("/send_file")
def send_file():
    file = io.BytesIO()
    file.write(b"Hello, World!")
    file.seek(0)
    return send_file(file, attachment_filename=f"example.txt", as_attachment=True)

And then I expect you'll do something with it in Javascript:

fetch('https://example.com/send_file')
.then(res => res.blob())
.then(blob => {
    // Do something
});
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
  • Thanks. Your solution worked. But When I am sending file object, it is getting unwrapped over the network. I am getting directly the content of the file in the frontend. Can you suugest solution for this? – Junior_K27 Aug 16 '19 at 07:15
  • @Junior_K27 what do you intend to do with the file? What kind of file is it? – Halvor Holsten Strand Aug 16 '19 at 07:20
  • It could be any file like pdf,txt,png,mp4. I am uploading a file and again displaying it in the browser. While I am sending file object back to frontend to display it's getting unwrapped over the network . – Junior_K27 Aug 16 '19 at 07:30
  • @Junior_K27 how do you intend to display an arbitrary file? Lets say it was an image, then you could do [as in this answer](https://stackoverflow.com/a/44069294/2732991). If it is PDF maybe [try this answer](https://stackoverflow.com/a/21730535/2732991). I feel it depends on what and how. – Halvor Holsten Strand Aug 16 '19 at 07:37
  • I am able to display the file correctly. My problem is, unwrapped object is passed over the network which shouldn't happen in my case. I want to send object and then I can unwrap it in the frontend and display.Basically i want some wrapper around the content of file. – Junior_K27 Aug 16 '19 at 09:21
0

http://blog.luisrei.com/articles/flaskrest.html

Please check this link and refer "RESPONSES" subtitle.

from flask import Response

@app.route('/hello', methods = ['GET'])
def api_hello():
    data = {
        'hello'  : 'world',
        'number' : 3
    }
    js = json.dumps(data)

    resp = Response(js, status=200, mimetype='application/json')
    resp.headers['Link'] = 'http://luisrei.com'

    return resp
Reinis
  • 477
  • 1
  • 5
  • 13