cURL的--remote-name等选项与浏览器行为不符,如何获取正确文件名?
问题
我需要下载远程文件并获取其文件名。通过浏览器下载目标文件时,能得到正确文件名amazon-corretto-8.402.08.1-linux-x64.tar.gz,但使用以下cURL命令下载时:
curl --location --remote-name --remote-header-name --write-out '%{filename_effective}' https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect
下载的文件名为redirect。查看响应头(执行curl --location -sI https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect)后发现,响应中缺少--remote-header-name依赖的Content-Disposition头。
我需要获取文件名来确定文件类型(如tar.gz、bin)以进行后续处理,请问有实现方法吗?
解决方案
方法1:解析最终重定向URL提取文件名
先获取最终跳转的完整URL,再从中截取文件名:
# 获取最终重定向URL final_url=$(curl --location -s -w '%{url_effective}' -o /dev/null https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect) # 提取URL末尾的文件名 filename=$(basename "$final_url") # 下载文件并使用该文件名 curl --location -o "$filename" https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect # 输出文件名供后续处理 echo "$filename"
方法2:移除--remote-header-name参数让cURL自动推断
--remote-header-name会强制cURL优先从Content-Disposition头取文件名,而忽略URL。移除该参数后,cURL会自动从最终重定向的URL中提取文件名:
curl --location --remote-name --write-out '%{filename_effective}' https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect
执行后文件会被保存为正确的amazon-corretto-8.402.08.1-linux-x64.tar.gz,%{filename_effective}也会输出该文件名。
方法3:通过Foojay API直接查询元数据
调用Foojay的disco API获取文件元数据,直接提取文件名:
# 需提前安装jq工具解析JSON filename=$(curl -s https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e | jq -r '.filename') # 下载文件 curl --location -o "$filename" https://api.foojay.io/disco/v3.0/ids/8e9bf72c045d59ae13d4d88e4b65b01e/redirect
内容的提问来源于stack exchange,提问作者JackPGreen
相关产品推荐
相关产品推荐

