-1

I want to serve many files in a folder and thats possible with app.use('/files', express.static('uploads'));.

All my files have an uuid as suffix for example: 73694640-44e9-448d-bf2f-29148b59180b_myfile.txt.

Is there a short way to serve all files in this folder but when downloading them, the filename should be without the suffix/uuid?

Like http://localhost/files/73694640-44e9-448d-bf2f-29148b59180b_myfile.txt will download myfile.txt.

  • there should be some logic in your code, right which is adding the UUID? – Ravi Kumar Gupta Oct 01 '21 at 12:24
  • @RaviKumarGupta The uuid get`s added to the file name to prevent duplication when the files get's uploaded. I think I need to edit my question a bit.. – somedude324334 Oct 01 '21 at 12:26
  • I got your point. That's what I am asking - is UUID being added to your written code or some library? If its done by your code, you can edit the file name to remove the suffix also. – Ravi Kumar Gupta Oct 01 '21 at 12:30

2 Answers2

1

I found the answer here : Download a file from NodeJS Server using Express . Both using express and without using express.

It is too simple if you are using Express. Here is the documentation for res.download. I can't believe that the solution is just one line of code :

res.download('/path/to/file.txt', 'newname.txt');

  • Thanks for the info how to do that :) I did write this code to replace the serve code: `app.get('/files/:file', (req, res) => { res.download(`./uploads/${req.params.file}`, req.params.file.substring(req.params.file.indexOf('_') + 1)) })`. PS: You can copy this code to your answer to make it complete. – somedude324334 Oct 01 '21 at 12:47
0

Here is the code that can make this happen:

app.get('/files/:file', (req, res) => {
    res.download(`./uploads/${req.params.file}`, req.params.file.substring(req.params.file.indexOf('_') + 1))
})

I removed the app.use('/files', express.static('uploads')); because the new route handles all the files in the uploads folder.

app.get('/files/:file', (req, res) => { takes the filename from the url as parameter. With this we can just send the file as download with res.download(`./uploads/${req.params.file}.

The filename can be edit to remove the suffix. First we look where the first _ apears, take this index + 1 and create a substring of the string after the suffix: req.params.file.substring(req.params.file.indexOf('_') + 1)