-1

I have a function that allows you to create a folder in the directory where the server is located, and upload files there And I'm trying to access them via a direct link, like this

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

Because, the file is located here enter image description here

But why can't I access it?

Cannot GET /attachments/1618413024408--1.jpg
Alice
  • 211
  • 2
  • 11
  • Does this answer help? [static files with express.js](https://stackoverflow.com/q/10434001/996081) – cbr Apr 14 '21 at 15:45
  • Just as a precaution, be aware that it is not a good idea to store user uploaded files directly on your server, as they may be rewritten every time you redeploy your server. – Shmili Breuer Apr 14 '21 at 15:57

2 Answers2

1

Express itself provides an easy to use implementation for this express.static(root, [options]).

Simply add this add the right position in your code:

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

Make sure that path.join(__dirname, 'attachments') points to the right directory (with a simple console.log) otherwise just adjust it.

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

tjarbo
  • 711
  • 4
  • 13
0

try to use express function sendFile

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

something like this

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'
      }
    })
})

or express download function https://expressjs.com/en/api.html#res.download

Alan Millirud
  • 1,049
  • 7
  • 14