How to serve static files with Vapor?

I am trying to write a server side application using Swift and Vapor environment. However, I cannot figure out how to serve static files using Vapor. It is not enough just to move them to the Public or Resources directory.

How can i do this?

UPD. I took the steps that Tanner Nelson suggested, but it still doesn't work.

What I have tried so far:

  • vapor build and vapor run (using Vapor Toolbox v0.6.1).

  • ./build/debug/App from the root directory (which contains Package.swift ).

  • Launch in Xcode 8 beta after editing the scheme proposed by Tanner Nelson.

In all these cases, I get the error {"error":true,"message":"Page not found"}

I have a vapor_logo.png file inside the Public folder, as well as the same file inside the Public/images/ folder. I try to request it and it fails. The requests I made are: http://localhost:8080/image/vapor_logo.png and http://localhost:8080/vapor_logo.png . However, other routes work fine.

UPD 2. Well, these were all my mistakes. Firstly, the file, which I think is called vapor_logo.png , was actually called vapor-logo.png . Secondly, business matters when you make a request. I also tried to request a file named IMG_8235.JPG , but recorded the file extension as jpg , so I got an error.

So, just to repeat: if you experience the same problem as me, follow the Tanner Nelson answers and make sure that the name of the requested file exactly matches the name of the file on disk.

+8
swift vapor
source share
1 answer

The structure of the sailing folder from Docs :

 . ├── App │ └── main.swift │ └── ... ├── Public ├── Resources └── Package.swift 

Any files in the Public folder will be served by default if no routes have been registered that conflict with the file name.

For example, if you have a Public/foo.png and the following main.swift file:

 import Vapor let drop = Droplet() drop.get("welcome") { request in return "Hello, world" } drop.serve() 

A localhost/welcome request will return "Hello, world" , and a localhost/foo.png will return foo.png .

If this does not work properly, it is likely that your working directory is not configured properly. This can happen if you start the project from Xcode or use it from the command line from a folder that is not the project root directory.

To fix Xcode, go to Schemes > App > Edit Scheme > Run > Options > Working Directory > [x] Use Custom Working Directory and make sure that the directory is installed in the root of your project (where Package.swift is located).

Xcode working directory

To fix it when starting from the command line, make sure that you start the application from the root directory. that is, the start command should look something like .build/debug/App , since the .build folder is in the root directory.

+14
source share

All Articles