【问题标题】:How can I allow a user to download a file from a link in express?如何允许用户从 express 链接下载文件?
【发布时间】:2021-04-14 15:33:55
【问题描述】:

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

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

因为,文件位于此处

但为什么我无法访问它?

Cannot GET /attachments/1618413024408--1.jpg

【问题讨论】:

  • 这个答案有帮助吗? static files with express.js
  • 作为预防措施,请注意,将用户上传的文件直接存储在您的服务器上并不是一个好主意,因为每次重新部署服务器时它们都可能被重写。

标签: node.js reactjs express get mern


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试使用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

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2012-10-08
      • 2017-02-10
      • 2020-06-04
      • 2010-10-15
      • 2020-04-01
      • 2014-02-26
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多