Skip to content

Express response.download

TIP

将 path 处的文件作为 "attachment" 传输。

Express
res.download(path, [filename], [fn])

将 path 处的文件作为 "attachment" 传输。通常,浏览器会提示用户下载。默认情况下,Content-Disposition 标头 "filename=" 参数派生自 path 参数,但可以用 filename 参数覆盖。如果 path 是相对的,那么它将基于进程的当前工作目录。

该方法在传输完成或发生错误时调用回调函数 fn(err)。如果指定了回调函数并且发生错误,则回调函数必须通过结束请求-响应循环或将控制权传递给下一个路由来显式处理响应过程。

Express
res.download('/report-12345.pdf')

res.download('/report-12345.pdf', 'report.pdf')

res.download('/report-12345.pdf', 'report.pdf', (err) => {
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
})