5
votes

So I'm trying to set up upload functionality on the website. However, I'm struggling with the location where to keep the uploaded files.

I followed the phoenix guidelines, added plug Plug.Static, at: "/files", from: "/media", gzip: false to my Endpoint file, and created the /media folder in the root of the project. But keep getting error: no route found for GET /files/3-news.jpg (Kz.Router) .

I'm not sure what I'm doing wrong, maybe the location of /media folder is incorrect? I've put it into the root, where others folders are, such as web, priv, test, etc. Is it the right place? Or the path has to be full OS path, like /Users/Jack/Desktop/myApp/media/ ?

Thanks in advance guys, and any advise appreciated!

P.S. I'm able to upload files with File.cp(upload.path, "media/#{file_name}") and they appear in /media, but still can't access them via http://localhost:4000/files/4-news.jpg

2

2 Answers

8
votes

Just figured it out. My mistake was placing plug Plug.Static, at: "/files", from: "media/" at the bottom of Endpoint file, but it should be placed under the existing Plug.Static, like this:

plug Plug.Static,
at: "/", from: :myApp, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)

plug Plug.Static, at: "/files", from: "media/"

Or at least before the plug myApp.Router! Then you can access all the files you need.

0
votes

We can also put the path in controller and copy it to whatever path

path_upload = upload["docfile"]

IO.inspect path_upload.filename, label: "Photo upload information"
File.cp(path_upload.path, Path.absname("uploads/#{path_upload.filename}"))