本文共 1189 字,大约阅读时间需要 3 分钟。
express发送文件
Express provides a handy method to transfer a file as attachment: Response.download()
.
Express提供了一种方便的方法来将文件作为附件传输: Response.download()
。
Once a user hits a route that sends a file using this method, browsers will prompt the user for download.
一旦用户点击使用此方法发送文件的路由,浏览器就会提示用户进行下载。
The Response.download()
method allows you to send a file attached to the request, and the browser instead of showing it in the page, it will save it to disk.
Response.download()
方法允许您发送附加到请求的文件,并且浏览器会将其保存到磁盘,而不是在页面中显示。
app.get('/', (req, res) => res.download('./file.pdf'))
In the context of an app:
在应用程序的上下文中:
const express = require('express')const app = express()app.get('/', (req, res) => res.download('./file.pdf'))app.listen(3000, () => console.log('Server ready'))
You can set the file to be sent with a custom filename:
您可以将文件设置为使用自定义文件名发送:
res.download('./file.pdf', 'user-facing-filename.pdf')
This method provides a callback function which you can use to execute code once the file has been sent:
此方法提供了一个回调函数,一旦文件发送完毕,便可以使用该函数执行代码:
res.download('./file.pdf', 'user-facing-filename.pdf', (err) => { if (err) { //handle error return } else { //do something }})
翻译自:
express发送文件
转载地址:http://whqgb.baihongyu.com/