node.js - 如何允许用户从 express 链接下载文件?
问题描述
我有一个功能,允许您在服务器所在的目录中创建一个文件夹,并在那里上传文件我正在尝试通过直接链接访问它们,就像这样
http://localhost:5000/attachments/1618413024408--1.jpg
但是为什么我不能访问它?
Cannot GET /attachments/1618413024408--1.jpg
解决方案
Express 本身为此提供了一个易于使用的实现express.static(root, [options])
。
只需在代码中添加正确的位置:
app.use('/attachments', express.static(path.join(__dirname, 'attachments')))
确保它path.join(__dirname, 'attachments')
指向正确的目录(使用简单的 console.log),否则只需调整它。
推荐阅读
- java - 鉴于我已经拥有密钥,HashMap 正在获取密钥
- r - 错误可能来自在函数中使用 which 或未在函数中指定变量
- scala - 试图理解 Scala 中的 Range 集合,以及为什么在 Scala v2.13 而不是 v2.11 中分配数据类型时会出现错误
- python - 值错误但在执行 RepeatedKFold 后无法弄清楚哪里出错了
- javascript - 如何突出显示由于文本溢出而隐藏在...下的文本:省略号
- c++ - STL 容器内的特征对象
- regex - 用bash中的环境变量替换所有字符串正则表达式匹配
- sql - SQL Query 在 SELECT * 中不返回实体,但在指定 ID 时返回实体
- javascript - 反应 img src 在手机上显示损坏的图像,但在 PC 上加载正常
- firebase - Firestore - 通过在本地进行更改,然后将数据推送到服务器来减少写入和读取量