wget用Content-Disposition字段值为文件名
基本用法
wget可以通过--content-disposition参数使用HTTP响应头中的Content-Disposition字段来设置下载文件的文件名。
wget [--no-check-certificate] --content-disposition 'url'
详细说明
Content-Disposition头字段
Content-Disposition是HTTP响应头中的一个字段,用于指示如何处理响应内容。当服务器希望浏览器下载文件而不是显示时,会使用这个字段。
常见的格式:
Content-Disposition: attachment; filename="example.pdf"
Content-Disposition: attachment; filename*=UTF-8''%E4%BE%8B%E5%AD%90.pdf
参数说明
--content-disposition: 启用对Content-Disposition头的支持--no-check-certificate: 跳过SSL证书验证(可选,用于自签名证书)
实际应用场景
1. 动态文件下载
当下载链接指向动态生成的文件时,服务器会通过Content-Disposition指定正确的文件名:
wget --content-disposition "https://example.com/download.php?id=123"
2. 中文文件名处理
对于包含中文字符的文件名,Content-Disposition可能会使用URL编码:
wget --content-disposition "https://example.com/中文文件.pdf"
wget会自动处理URL编码的文件名。
3. 批量下载
结合其他参数使用:
# 后台下载,使用Content-Disposition文件名
wget -b --content-disposition "https://example.com/file.zip"
# 限制下载速度,使用Content-Disposition文件名
wget --limit-rate=100k --content-disposition "https://example.com/large-file.iso"
高级用法
结合其他wget参数
# 断点续传,使用Content-Disposition文件名
wget -c --content-disposition "https://example.com/big-file.tar.gz"
# 递归下载,使用Content-Disposition文件名
wget -r --content-disposition "https://example.com/files/"
脚本中的应用
在shell脚本中批量处理下载任务:
#!/bin/bash
URLS=(
"https://example.com/file1.pdf"
"https://example.com/file2.doc"
"https://example.com/数据.xlsx"
)
for url in "${URLS[@]}"; do
echo "正在下载: $url"
wget --content-disposition "$url"
done
注意事项
1. 安全性考虑
- 谨慎使用
--no-check-certificate参数,可能存在安全风险 - 建议在可信网络环境中使用
2. 文件名冲突
如果多个URL返回相同的文件名,wget会自动添加数字后缀:
document.pdf
document(1).pdf
document(2).pdf
3. 编码问题
- 确保终端支持UTF-8编码以正确显示中文文件名
- 在某些系统上可能需要额外的配置
4. 服务器支持
并非所有服务器都正确设置Content-Disposition头,某些情况下可能需要手动指定文件名:
# 如果Content-Disposition不可用,使用-O参数指定文件名
wget -O custom-name.pdf "https://example.com/download"
故障排除
常见问题
文件名显示乱码
# 设置locale export LANG=zh_CN.UTF-8下载失败
# 检查HTTP头 curl -I "https://example.com/download"文件名被截断
# 检查服务器返回的完整Content-Disposition头 wget --spider --server-response "https://example.com/download"
替代方案
如果wget不可用,也可以使用其他工具:
使用curl
curl -J -O "https://example.com/download"
使用Python
import requests
import os
url = "https://example.com/download"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
filename = response.headers.get('content-disposition', '').split('filename=')[-1].strip('"')
with open(filename, 'wb') as f:
f.write(response.content)