Chrome 内置 PDF 查看器下载按钮如何为鉴权 PDF 使用自定义文件名?
结论
用 blob: URL 时,Chrome 内置 PDF 查看器自带下载按钮的文件名没法可靠自定义。查看器会拿加载 URL 的最后路径段当文件名;XHR/fetch 返回的 Content-Disposition 只有 Angular 能看到,不会传给 PDF viewer。用 Service Worker + Cache API 伪造出带文件名的 URL,也拦不住查看器下载按钮触发的浏览器下载流程。想保留原生下载按钮又拿到自定义文件名,需要让 iframe 加载真实 URL,最后一段路径就是目标文件名,再用短期签名 URL 或作用域受限的 cookie 做鉴权。iframe 本身不能直接发送 Authorization 头。
为什么 blob URL 不行
URL.createObjectURL(blob)会生成blob:http://origin/<uuid>,查看器只能从 URL 里读到<uuid>.pdf。- 原始响应头
Content-Disposition在 Angular 的 HTTP 响应里能看到,但 PDF 查看器看不到原始响应头。 - 在 blob URL 后面追加 query 或 fragment 并不可靠,查看器会忽略它们。
- Service Worker + Cache API 可能让加载路径看起来像
/name.pdf,但下载按钮走的是浏览器下载流程,fetch事件不一定触发(Chromium issue 40410035),还容易把 MIME 弄成.htm。 - 所以,你原来的理解基本没错:不要依赖
Content-Disposition或 blob URL 控制原生查看器的下载名。不同 Chrome 版本细节可能有差异,但实际结论一致。
推荐做法:真实 URL + 短期签名 URL
- Angular 继续用 Bearer token 调后端 API,换取一个短期可用的 PDF URL。
- 该 URL 的最后路径段是 URL 编码后的文件名,例如
/equipment/123/preview/%E6%B3%B5%E7%AB%99%E6%A3%80%E6%9F%A5.pdf?exp=...&sig=...。 - iframe 的
src指向该 URL。 - 后端校验签名,返回
Content-Type: application/pdf、Content-Disposition: inline,并支持 Range 请求。
Angular 侧示例:
getPdfPreviewUrl(id: number): Observable<{ url: string }> {
return this.http.get<{ url: string }>(`${this.baseUrl}/${id}/equipment_pdf_preview_url`);
}
viewPdf(equipment_id: number): void {
this.equipmentService.getPdfPreviewUrl(equipment_id).subscribe({
next: (res) => {
this.pdfUrl = this.sanitizer.bypassSecurityTrustResourceUrl(res.url);
},
error: (err) => {
console.error(err);
this.pdfUrl = null;
this.snackbar.open('Failed to load PDF preview.', 'Okay', { duration: 2500 });
},
});
}
模板:
<iframe [src]='pdfUrl' width='100%' height='800'></iframe>
Quart 侧示例(只保留关键逻辑):
import hmac
import hashlib
import time
from io import BytesIO
from urllib.parse import quote
from quart import abort, request, send_file
SECRET_KEY = b'replace-with-secret'
def make_signed_pdf_url(equipment_id: str, file_name: str, ttl: int = 300) -> str:
exp = int(time.time()) + ttl
msg = f'{equipment_id}:{file_name}:{exp}'.encode()
sig = hmac.new(SECRET_KEY, msg, hashlib.sha256).hexdigest()
encoded_name = quote(file_name, safe='')
return f'/equipment/{equipment_id}/preview/{encoded_name}?exp={exp}&sig={sig}'
@bp.route('/<equipment_id>/equipment_pdf_preview_url')
@authorization.needs_authorization
async def equipment_pdf_preview_url(equipment_id, *args, **kwargs):
equipment = equipments_service.get_by_id(equipment_id)
if equipment is None:
return to_response(f'No equipment found with id {equipment_id}', 404)
file_name = f'{equipment.name}.pdf'
return {'url': make_signed_pdf_url(equipment_id, file_name)}
@bp.route('/<equipment_id>/preview/<file_name>')
async def equipment_pdf_preview_signed(equipment_id, file_name):
exp = int(request.args.get('exp', '0'))
sig = request.args.get('sig', '')
if exp < int(time.time()):
abort(403)
msg = f'{equipment_id}:{file_name}:{exp}'.encode()
expected = hmac.new(SECRET_KEY, msg, hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
abort(403)
pdf = get_equipment_file(equipment_id, watermark_text='IN PLANNING')
pdf_bytes = bytes(pdf.output())
return await send_file(
BytesIO(pdf_bytes),
mimetype='application/pdf',
as_attachment=False,
download_name=file_name,
conditional=True,
)
这里的签名用解码后的 file_name,路由也要拿到同一个值。文件名必须清洗,不能包含 /、\、控制字符或 ..,并保留 .pdf 扩展名。send_file 的 conditional=True 用于条件请求和 Range 支持;如果使用对象存储或反向代理,确认它们也支持 Range。
cookie 方案
如果不能让 token 出现在 URL 里,可以换个做法:Angular 继续用 Bearer token 调接口,后端设置一个短期、路径受限的 HttpOnly cookie,比如 Path=/equipment/<id>/preview/,然后让 iframe 加载 /equipment/<id>/preview/<filename>.pdf。同站场景下 SameSite=Lax 通常够用;跨站 iframe 需要 SameSite=None; Secure,还要考虑浏览器对第三方 cookie 的限制。不要把长期 bearer token 直接放进 cookie,应该用短时效、单用途或限定路径的会话凭据。
容易踩坑的地方
- 查看器下载时可能重新请求 URL,也可能发多个 Range 请求。签名 URL 不要做成一次性有效;TTL 要覆盖预览和下载,并支持重复的 GET/HEAD/Range。
- 大 PDF 要支持
Accept-Ranges: bytes、206 Partial Content和正确的Content-Range。一次性 token 会让后续 Range 请求失败。 - URL 路径最后一段就是文件名,记得做 URL 编码;同时设置
Content-Disposition: inline和filename*=UTF-8''...做兼容。不要用attachment,否则 iframe 可能直接下载,而不是预览。 - token 放在 query 里可能出现在访问日志和 Referer 中。用短 TTL,限定 equipment_id/用户,并在页面设置
Referrer-Policy: no-referrer。 - 跨域 iframe 要允许被嵌入:不要返回
X-Frame-Options: DENY,CSP 的frame-ancestors要包含前端源。cookie 方案还要处理 SameSite 和第三方 cookie 限制。 - 如果 PDF 是动态生成,注意多次请求内容一致、
Content-Length正确、ETag/Last-Modified 合理;敏感文件用Cache-Control: private, no-store或按需缓存。 - 如果业务上必须坚持
Authorization头,又不能用签名 URL 或 cookie,那原生查看器自带下载按钮就满足不了文件名要求;只能改用 PDF.js 这类自定义查看器,但这已经偏离原生查看器方案。
备注:内容仅供参考。
