Search code examples
swiftvapor

How to serve static files using Vapor?


I'm trying to write server side application using Swift and Vapor framework. However, I can't figure out, how to serve static files using Vapor. It's not enough to just move them to the Public or Resources directory.

How can I do that?

UPD. I performed steps which Tanner Nelson suggested but it still doesn't work.

What I tried so far:

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

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

  3. Run in Xcode 8 beta after editing scheme as Tanner Nelson suggested.

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

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

UPD 2. Well, that was all my mistakes. First, file that I think was called vapor_logo.png, actually was called vapor-logo.png. Second, case matters when you make a request. I also tried to request file with name IMG_8235.JPG but write file extension as jpg, so got an error.

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


Solution

  • Vapor folder structure from Docs:

    VaporApp
    ├── Package.swift
    ├── Resources
    │   ├── Views
    │   │   └── hello.leaf
    ├── Public
    │   ├── images (images resources)
    │   ├── styles (css resources)
    └── Sources
        └── ...
    

    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 file 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 request to localhost/welcome would return "Hello, world" and a request to localhost/foo.png would return foo.png.

    If this is not working properly, it's likely that your working directory is not configured properly. This can happen if you are running your project from Xcode or you are running it from the command line from a folder that is not the root directory of the project.

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

    Xcode working directory

    To fix when running from the command line, make sure you are running the application from the root directory. i.e., the run command should look something like .build/debug/App since the .build folder is located in the root directory.