简体   繁体   English

如何使用 Vapor 服务器端 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?如何使用服务器端 swift 下载文件?

I have tried this:我试过这个:

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

but result.body always = 0 elements但 result.body 总是 = 0 个元素

  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.您在这里走在正确的轨道上,但是result.body始终为空的原因是因为您的文件服务返回的是302重定向而不是文件本身。 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.最好的方法是将您的文件保存在您的 Vapor 应用程序的Public目录中,然后让您的客户端直接请求公共 URL,或者返回您自己指向它的302响应。

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.如果您明确想要隐藏文件的永久主页或例如执行身份验证,那么您可以使用 Vapor 自己的FileMiddleware作为指南从您自己的路径返回文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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