使用Express发送文件的方法

629 阅读1分钟

Express提供了一个方便的方法来传输文件作为附件:`Response.download()`。

Express提供了一个方便的方法来传输一个文件作为附件:Response.download()

一旦用户点击一个使用此方法发送文件的路由,浏览器就会提示用户下载。

Response.download() 方法允许你在请求中发送一个附件文件,浏览器不会在页面中显示它,而是将它保存到磁盘中。

app.get('/', (req, res) => res.download('./file.pdf'))

在一个应用程序的背景下。

const express = require('express')
const app = express()

app.get('/', (req, res) => res.download('./file.pdf'))
app.listen(3000, () => console.log('Server ready'))

你可以用一个自定义的文件名来设置要发送的文件。

res.download('./file.pdf', 'user-facing-filename.pdf')

该方法提供了一个回调函数,一旦文件被发送,你可以用它来执行代码。

res.download('./file.pdf', 'user-facing-filename.pdf', (err) => {
  if (err) {
    //handle error
    return
  } else {
    //do something
  }
})