如何使用蒸气响应图像?

时间:2018-08-22 21:26:54

标签: swift vapor

我只希望有一个控制器操作,其作用基本上与直接通过Public/文件夹访问图像相同。区别在于路由可以是您想要的任何路径,返回的图像将是在控制器功能内部确定的图像。但是如何建立适当的回应?

我的方法如下:

import Vapor

final class ImageController {
    func read(_ req: Request) throws -> Future<Data> {
        let directory = DirectoryConfig.detect()
        let promise = req.eventLoop.newPromise(Data.self)
        req.eventLoop.execute {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: directory.workDir)
                    .appendingPathComponent("Public", isDirectory: true)
                    .appendingPathComponent("image.png"))
                promise.succeed(result: data)
            } catch {
                promise.fail(error: error)
            }
        }
        return promise.futureResult
//        try req.content.encode(data, as: .png)
    }
}

但是在我看来,我过于复杂了,对吗?

2 个答案:

答案 0 :(得分:5)

但是如何创建适当的响应?

直接创建 Response 并设置 MediaType request.makeResponse(data, as: MediaType.png)

示例:

struct ImageController: RouteCollection {
    func boot(router: Router) throws {
        let imageRoutes = router.grouped("images")
        // GET /images/get-test-image
        imageRoutes.get("get-test-image", use: getTestImage)    
    }

    func getTestImage(_ request: Request) throws -> Response {
        // add controller code here 
        // to determine which image is returned
        let filePath = "/path/to/image18.png"
        let fileUrl = URL(fileURLWithPath: filePath)

        do {
            let data = try Data(contentsOf: fileUrl)
            // makeResponse(body: LosslessHTTPBodyRepresentable, as: MediaType)
            let response: Response = request.makeResponse(data, as: MediaType.png)
            return response
        } catch {
            let response: Response = request.makeResponse("image not available")
            return response
        }
    }
}

答案 1 :(得分:3)

另外两种方法:

  1. 使用Leaf部署映像的路由:

    route.get("/my/random/route") {
         request -> Future<View> in
         return try request.view().render("image", ["imgname":"image.png"])
    }
    

image.leaf包含:

<img src="#(imgname)">
  1. 重定向到Public中的原始位置:

    route.get("/my/random/route") {
        request -> Response in
        return request.redirect(to: "/image.png")
    }