swiftvaporserver-side-swift

How do I download a file and send a file using Vapor server side swift?


  1. How do I download a file using server side swift?

I have tried this:

let result = try drop.client.get("http://dropcanvas.com/ir4ok/1")

but result.body always = 0 elements

  1. How do I send a file?

I have tried this

drop.get("theFile") { request in 
   let file = NSData(contentsOf: "/Users/bob.zip")
   return file // This fails here
}

Solution

    1. Download a file.

    You are on the right track here, but the reason why result.body is always empty is because your file service is returning a 302 redirection rather than the file itself. You need to follow this redirection. Here is a simple implementation, specific to your use case only, which works:

      var url: String = "http://dropcanvas.com/ir4ok/1"
      var result: Response!
      while true {
        result = try drop.client.get(url)
        guard result.status == .found else { break }
        url = result.headers["Location"]!
      }
      let body = result.body
    
    1. Send a file.

    The very best method is to save your file in your Vapor app's Public directory, and either have your client request the public URL directly, or return a 302 response of your own pointing to it.

    If you expressly want to hide the permanent home of the file or e.g. perform authentication then you can return the file from your own route using Vapor's own FileMiddleware as a guide.