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
.
CodePudding user response:
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');
CodePudding user response:
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)