简体   繁体   中英

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
}
  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 eg perform authentication then you can return the file from your own route using Vapor's own FileMiddleware as a guide.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM