给前端提供一个文件下载接口时, 遇到了文件名乱码的问题, 几经折腾总算实现效果, 代码如下:
import requests
from flask import Response, jsonify, request, stream_with_context
from flask_login import login_required
from . import bp
from .models import Courseware
@bp.route("/courseware/download")
@login_required
def courseware_download():
"""
课件下载 GET
:param id: 课件id
"""
pk = request.args.get("id", type=int)
obj = Courseware.query.get(pk)
if not obj:
return jsonify(detail=f'Courseware(id={pk}) not found.'), 404
try:
url = f"{obj.domain.rstrip('/')}/{obj.filekey}" # 七牛云文件下载地址
r = requests.get(url, stream=True, timeout=500)
response = Response(
stream_with_context(r.iter_content(chunk_size=1024)),
content_type=r.headers["content-type"],
)
header = f'attachment; filename="{quote(obj.filename.encode())}"'
response.headers["Content-Disposition"] = header
return response
except Exception as e:
print("download file error:", e)
return jsonify(detail=str(e)), 422