【问题标题】:How to display image using AWS S3 and Vapor 3 and Leaf如何使用 AWS S3 和 Vapor 3 和 Leaf 显示图像
【发布时间】:2019-05-25 13:23:37
【问题描述】:

我已经设置了 AWS S3 存储桶,并且可以使用 Vapor 3 和 Postman 上传文件。我也可以使用 Vapor 3 和 Postman 获取文件,但我很难在浏览器上获取并实际显示文件(png -images)(我使用的是叶子)。

那么如何在视图上显示图像文件?我是 HTML、AWS S3 和 Vapor 的新手。

我正在使用:

  • 蒸汽 3
  • AWS S3
  • 叶包
  • S3 包
  • VaporExt 封装

我按照本教程设置了所有内容(get 请求和存储桶策略除外):https://fivedottwelve.com/blog/using-amazon-s3-with-vapor/

这是我的 Vapor 代码:

/// GET reguest
func preparePresignedImageUrl(request: Request) throws -> String {

    let baseUrl = awsConfig.url
    let imagePath = awsConfig.imagePath
    let fileName = "x.png"


    guard var url = URL(string: baseUrl) else {
        throw Abort(.internalServerError)
    }
    url.appendPathComponent(imagePath)
    url.appendPathComponent(fileName)

    print("url is \(url)")
    let headers = ["x-amz-acl" : "public-read"]


    let s3 = try request.makeS3Signer()
    let result = try s3.presignedURL(for: .GET, url: url, expiration: Expiration.hour, headers: headers)
    /// Retrieve file data from S3

    guard let presignedUrl = result?.absoluteString else {
        throw Abort(.internalServerError)
    }

    return presignedUrl

}

路线:

// GET request
 group.get("aws", "image", use: preparePresignedImageUrl) 

在邮递员中,当我向 presignedURL 发出 GET 请求时,它会给我一个状态码 200OK。

我的showImage.leaf 文件:

#set("content") {
<h1>#(title)</h1>

// Here some html to get the image path and display the image?
  <img>

}

#embed("base")

【问题讨论】:

  • 分享Future&lt;View&gt;的相关代码showImage.leaf和你正在使用的上下文模型,即允许你使用#(title)的上下文模型

标签: image amazon-web-services amazon-s3 vapor leaf


【解决方案1】:

所以我假设你有一个非常好的图片 URL。

让我们首先在GET /image 创建一个路由:

routes.get("image", use: image)

func image(_ request: Request) -> EventLoopFuture<View> {

}

为了正确渲染 Leaf 视图,我们需要一个包含 Leaf 变量数据的上下文。它看起来像这样:

struct ImageContext: Encodable {
    let title: String
    let imageURL: String
}

我们还需要编辑您的叶子文件,以便它使用上下文中的属性:

#set("content") {
<h1>#(title)</h1>
<img src="#(imageURL)">
}

#embed("base")

现在我们可以在没有新上下文的情况下渲染叶子文件并从路由处理程序返回结果视图。下面是 image 路由处理程序的实现:

func image(_ request: Request) -> EventLoopFuture<View> {
    let context = ImageContext(title: "Image", imageURL: preparePresignedImageUrl(request: request)
    return try request.view().make("showImage", context)
}

现在您应该可以从浏览器访问localhost:8080/image 并且图像将在那里!

【讨论】:

猜你喜欢
  • 2020-06-05
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多