You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从不含扩展名的URL中获取带对应扩展名的文件名?

获取无扩展名URL对应的带扩展名文件名

方法1:请求文件并读取响应头

直接请求目标URL,从响应头的两个核心字段提取文件信息:

  • 优先解析Content-Disposition:如果响应头包含该字段,通常会附带filename参数,比如attachment; filename="project.pdf",直接提取引号内的文件名即可。
  • fallback到Content-Type映射:如果没有Content-Disposition,可以根据Content-Type字段匹配对应扩展名,比如application/pdf对应.pdf,image/png对应.png。

示例Python代码:

import requests
from urllib.parse import unquote

url = "https://development.com:3000/api/file/92"
response = requests.get(url, stream=True)

filename = None
# 从Content-Disposition提取文件名
if 'Content-Disposition' in response.headers:
    disp_header = response.headers['Content-Disposition']
    if 'filename=' in disp_header:
        filename = unquote(disp_header.split('filename=')[1].strip('"'))

# 若未提取到,根据Content-Type映射扩展名
if not filename:
    type_ext_map = {
        'application/pdf': '.pdf',
        'image/png': '.png',
        'image/jpeg': '.jpg',
        'text/plain': '.txt',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx'
    }
    content_type = response.headers.get('Content-Type', '')
    ext = type_ext_map.get(content_type.split(';')[0], '')
    filename = f"92{ext}"

print(filename)

方法2:查询后端存储逻辑

如果这是自研API,直接查看后端代码或数据库结构:通常文件ID会和扩展名存在关联,比如数据库的file表可能包含id、extension字段,直接通过ID查询即可拿到扩展名。

方法3:枚举常见扩展名(仅应急)

如果无法请求接口或查文档,可以尝试给URL拼接常见扩展名,比如https://development.com:3000/api/file/92.pdf、https://development.com:3000/api/file/92.png,测试哪个返回有效文件,但这种方法效率低且不可靠。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:27:34