2

I am trying to send a pdf as an api response using Flask. However, I get a ERR_CONTENT_LENGTH_MISMATCH on the client side of the api. Maybe this is caused by the stream not being complete while the file is send to the client? Idk

from flask import Flask, send_file, make_response

app = Flask(__name__)

@app.route("/")
def get_pdf(request):
    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    pdf = Pdf.open('test.pdf')
    file = io.BytesIO()
    pdf.save(file)

    response = make_response(send_file(file, download_name="project_pdf", mimetype='application/pdf', as_attachment=True))
    response.headers.set('Access-Control-Allow-Origin', '*')

    return response
pjcunningham
  • 7,676
  • 1
  • 36
  • 49
Johann Süß
  • 97
  • 1
  • 12
  • 1
    Complete guess, but perhaps you need to rewind the stream before passing it to `send_file`, so right after `pdf.save(file)` do `file.seek(0)` then proceed to build the response. – v25 Aug 23 '21 at 14:35
  • 1
    What actually worked for me was to do `send_file(io.BytesIO(file.getbuffer()))`. I know this is kind of a hack though :) – Johann Süß Aug 25 '21 at 15:44

0 Answers0