3
  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
}
Just a coder
  • 15,480
  • 16
  • 85
  • 138
  • try also to join the slackchannel for vapor help – muescha Jan 29 '17 at 20:11
  • `result.body` is the right property? here they use `data` http://stackoverflow.com/questions/41868625/vapor-client-get-transform-and-return-json – muescha Jan 29 '17 at 20:16

2 Answers2

3
  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.

zekel
  • 9,227
  • 10
  • 65
  • 96
tobygriffin
  • 5,339
  • 4
  • 36
  • 61
1

A file can also be returned on an authenticated route like this:

let fileId: String = "abcd123"

func getFile(on req: Request) throws -> Future<Response> {
    let directory = try req.make(DirectoryConfig.self)
    let path = directory.workDir + Constants.filesPath + fileId + ".pdf"

    return try req.streamFile(at: path)
}
jstorm31
  • 111
  • 2
  • 3