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

烂漫一生 提交于 2020-02-28 08:08:27

问题


  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:


  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.




回答2:


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


来源:https://stackoverflow.com/questions/41917803/how-do-i-download-a-file-and-send-a-file-using-vapor-server-side-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!