这里是带有 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)
以下是curl命令:
λ 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
如何使用curl接收文件?
写入数据后,指针移动到文件中的下一个位置。这意味着在读取数据以使其可供下载之前,指针指向末尾并且不再读取数据。所以下载失败。为了提供文件下载,必须使用
seek(0)
将文件内的指针重置到开头。
attachment_filename
的 send_file()
属性现已弃用,并已被 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')