我如何允许用户从 link 快速下载文件?

How can I allow a user to download a file from a link in express?

我有一个功能可以让你在服务器所在的目录下创建一个文件夹,然后上传文件到那里 我正在尝试通过直接 link 访问它们,就像这样

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

因为,文件位于此处

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

Cannot GET /attachments/1618413024408--1.jpg

尝试使用 express 函数 sendFile

https://expressjs.com/en/api.html#res.sendFile

像这样

app.use('/attachments/:filename', (req, res) => {
   const myIms = <path to directory>
   const filePath = myIms + '/attachments/' + req.filename
    res.sendFile(filePath, {
      headers: {
          'Content-Type': 'image/jpg'
      }
    })
})

或表示下载功能https://expressjs.com/en/api.html#res.download

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