You need to enable JavaScript to run this app. Flask send_file提供USDZ文件,Chrome正常下载但Safari无法打开页面求助
优惠活动
大模型
产品
解决方案
定价
更多

Flask send_file提供USDZ文件,Chrome正常下载但Safari无法打开页面求助

解决Safari中Flask USDZ文件下载失败的问题

针对你遇到的Chrome能正常下载、Safari提示无法打开页面的问题,可以从以下几个方面调整代码:

1. 修正attachment_filename参数

当前代码中attachment_filename=data["url"]可能传入的是文件路径(比如/tmp/xxx.usdz),Safari对文件名格式要求更严格,需要传入纯文件名且带.usdz后缀,不能包含路径字符。

修改代码:

@app.route("/make_usd", methods=['GET'])
def make_usd():
    data = usd.create_usd(1, 2, 0.05)
    # 从路径中提取纯文件名
    filename = data["url"].split("/")[-1]
    response = make_response(send_file(
        data["url"],
        mimetype="model/vnd.usdz+zip",
        attachment_filename=filename,
        as_attachment=True
    ))
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response

2. 显式设置Content-Disposition头

Safari对响应头格式的兼容性要求更高,手动设置Content-Disposition可以避免Flask自动生成的格式不匹配:

@app.route("/make_usd", methods=['GET'])
def make_usd():
    data = usd.create_usd(1, 2, 0.05)
    filename = data["url"].split("/")[-1]
    response = make_response(send_file(
        data["url"],
        mimetype="model/vnd.usdz+zip",
        as_attachment=True
    ))
    # 手动指定下载文件名,确保转义格式正确
    response.headers["Content-Disposition"] = f"attachment; filename=\"{filename}\""
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response

3. 改用send_from_directory确保文件读取正常

如果文件是临时生成的,使用send_from_directory比直接send_file更稳妥,能避免路径权限或解析问题:

import os
from flask import send_from_directory

@app.route("/make_usd", methods=['GET'])
def make_usd():
    data = usd.create_usd(1, 2, 0.05)
    file_path = data["url"]
    file_dir = os.path.dirname(file_path)
    filename = os.path.basename(file_path)
    
    response = make_response(send_from_directory(
        directory=file_dir,
        path=filename,
        mimetype="model/vnd.usdz+zip",
        as_attachment=True
    ))
    response.headers["Content-Disposition"] = f"attachment; filename=\"{filename}\""
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response

4. 禁用缓存适配Safari特性

Safari对缓存的处理逻辑更严格,添加禁用缓存的响应头可以避免旧缓存导致的异常:

# 在生成response后添加以下头信息
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"

内容的提问来源于stack exchange,提问作者glemoulant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:25:19