首页 > 解决方案 > 如何允许用户从 express 链接下载文件?

问题描述

我有一个功能,允许您在服务器所在的目录中创建一个文件夹,并在那里上传文件我正在尝试通过直接链接访问它们,就像这样

http://localhost:5000/attachments/1618413024408--1.jpg

因为,文件位于此处 在此处输入图像描述

但是为什么我不能访问它?

Cannot GET /attachments/1618413024408--1.jpg

标签: node.jsreactjsexpressgetmern

解决方案


Express 本身为此提供了一个易于使用的实现express.static(root, [options])

只需在代码中添加正确的位置:

app.use('/attachments', express.static(path.join(__dirname, 'attachments')))

确保它path.join(__dirname, 'attachments')指向正确的目录(使用简单的 console.log),否则只需调整它。

文档:https ://expressjs.com/en/starter/static-files.html


推荐阅读