Search code examples
pythonweb-servicesflaskcurl

How to receive file send from flask with curl?


Here the server side code with python & flask:

from flask import Flask, request, send_file
import io
import zipfile
import bitstring

app = Flask(__name__)

@app.route('/s/',  methods=['POST'])
def return_files_tut():
    try:
        f = io.BytesIO()
        f.write("abcd".encode())
        return send_file(f, attachment_filename='a.ret.zip')
    except Exception as e:
        return str(e)

if __name__ == '__main__':
    app.run(debug=True)

Bellowing is curl command:

λ curl -X POST  http://localhost:5000/s/ -o ret.tmp
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     4    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (18) transfer closed with 4 bytes remaining to read

How should I use curl to receive the file?


Solution

  • When data is written, the pointer moves to the next position in the file. This means that before the data is read to make it available as a download, the pointer points to the end and no further data is read. So the download fails. In order to offer the file as a download, the pointer within the file must be reset to the beginning using seek(0).

    The attachment_filename attribute of send_file() is now deprecated and has been replaced by download_name.

    @app.post('/s/')
    def return_files_tut():
        f = io.BytesIO()
        f.write("abcd".encode())
        f.seek(0)
        return send_file(f, download_name='a.ret.zip')