Using A Wildcard Route Param to Download Storage Images
In This Lesson
We'll learn how we can utilize a wildcard route parameter to dynamically download images that've been uploaded and stored within our application storage.
When I try to access uploaded file, for example /storage/avatars/filename.png, without a route or controller, the file displays just fine. The StorageController isn’t called.
Finally, I get this error when I try to delete a movie’s poster : 'ENOENT: no such file or directory, unlink', I think the error comes from this line: 'await unlink(app.makePath('storage', movie.posterUrl))'. The generated path seems to be incorrect.
But I don’t understand why it seems to work for you.
If you're able to directly access the file via the URL without going through a route definition, that leads me to believe the file is actually within your public directory. Files within this directory are made accessible by the AdonisJS static file server.
That would also explain the "no such file" error on the attempted deletion, as app.makePath('storage') is going to be looking in the ~/storage directory directly off your application root, not within the public directory.
Can't say for certain though - just making an educated guess based on the info provided.
I don’t have a public directory, only storage at the root of the project.
The line router.get('/storage/*', [StorageController, 'show']).as('storage.show') is commented, and I can still access my downloaded files in that directory. 🤔
And for file deletion, it seems like the makePath method generates the following path: .../storage/storage/posters/filename.png since posterUrl also contains /posters . So, I used app.makePath('.', movie.posterUrl) instead, and it works. 😁
Sorry for the delayed response! Are you able to share the repo url? Neither should be the case, and I can't immediately think of anything that would cause either of those.
That's strange. I have the exact same code as you. But just to confirm, if I understood correctly (and correct me if I'm wrong), when we save a movie's poster, we use the following lines in the movie service:
So, the generated path will contain storage twice. As a result, since no file is located in storage/storage/posters, the deletion will not work. Right? Or did I misunderstand?
I'm so sorry, my head was in the wrong spot! You're absolutely right, the /storage gets added to the saved value in the database so the unlink should be:
await unlink(app.makePath('.', movie.posterUrl))
Copied!
Terribly sorry for the confusion there! I'll make a note to correct this lesson.