在服务端响应中,告诉前端这是一个需要被下载的文件(而不是直接展示),需要通过 HTTP 头部(Headers) 进行控制。以下是几种常见的实现方式:
1. 基础方法:Content-Disposition
关键是通过设置 Content-Disposition: attachment
,并可选指定文件名:
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="example.pdf"
Content-Length: 12345
<文件二进制数据>
attachment
:强制浏览器下载文件(而非预览)。filename
:指定下载时的默认文件名(需注意文件名中的特殊字符需用""
包裹)。
2. 结合正确的 Content-Type
根据文件类型设置对应的 MIME 类型,例如:
- PDF 文件:
Content-Type: application/pdf
- Excel 文件:
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- 通用二进制流(未知类型时):
Content-Type: application/octet-stream
3. 代码示例(不同语言)
Node.js (Express)
res.setHeader('Content-Disposition', 'attachment; filename="file.pdf"');
res.setHeader('Content-Type', 'application/pdf');
fs.createReadStream('/path/to/file.pdf').pipe(res);
Python (Flask)
from flask import send_file
@app.route('/download')
def download():
return send_file(
"/path/to/file.pdf",
as_attachment=True,
download_name="file.pdf"
)
Java (Spring Boot)
@GetMapping("/download")
public ResponseEntity<Resource> download() {
File file = new File("/path/to/file.pdf");
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"")
.body(new FileSystemResource(file));
}
PHP
header('Content-Disposition: attachment; filename="file.pdf"');
header('Content-Type: application/pdf');
readfile('/path/to/file.pdf');
4. 前端处理
前端通过 <a>
标签或 window.open()
触发下载:
<a href="/api/download" download="custom-filename.pdf">点击下载</a>
或通过 JavaScript:
fetch('/api/download')
.then(response => response.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'custom-filename.pdf';
a.click();
});
注意事项
- 文件名编码:
- 如果文件名包含非ASCII字符(如中文),需使用
filename*=UTF-8''encoded-name
:
Content-Disposition: attachment; filename*=UTF-8''%E6%96%87%E6%A1%A3.pdf
- 如果文件名包含非ASCII字符(如中文),需使用
- 大文件传输:
- 使用流式传输(如 Node.js 的
stream.pipe()
)避免内存溢出。
- 使用流式传输(如 Node.js 的
- 安全限制:
- CDN或反向代理可能会修改头部,需确保配置允许这些头部的传递。
通过以上方法,可以确保浏览器正确处理文件下载行为。
内容由零声教学AI助手提供,问题来源于学员提问