使用 PostgreSQL 在 Vapor 3 中上传图像

Image Upload in Vapor 3 using PostgreSQL

我正在关注这些 Martin Lasek 教程,现在我在 "image upload"。 好像没有人回答这个问题"How do you upload images i Vapor 3"

db连接正常,其他值都保存了。

这是我的创建方法:

    func create(_ req: Request) throws -> Future<Response> {

    return try req.content.decode(Question.self).flatMap { question in
        return question.save(on: req).map { _ in

            return req.redirect(to: "/form")
        }
    }
}

和型号:

final class Question: PostgreSQLModel {

var id: Int?
var questionText: String
var answers: [String]
var theme: String?
var imageName: String?
var imageData: File?

init(id: Int? = nil, questionText: String, answers: [String], theme: String, imageName: String?, imageData: File?) {

    self.id = id
    self.questionText = questionText
    self.answers = answers
    self.theme = theme
    self.imageName = imageName
    self.imageData = imageData
}

}

和叶子模板:

<form action="/save" method="POST" enctype="multipart/form-data" id="upload-form">
<input type="file" accept="image/png,image/jpg" name="image">
<input class="btn btn-success btn-block" type="submit" value="Legg til">
</form>

我知道需要一种管理文件的方法,原始图像字节为,

但是我怎么去那里呢?

我通过这样做设法获取了图像数据:

struct ImageRequest: Content {
    var imageData: Data
}

func analyizeImage(_ request: Request) throws -> Future<Response> {
    return try request.content.decode(ImageRequest.self).flatMap(to: Response.self, { [weak self] imageRequest in
        guard let image = NSImage(data: imageRequest.imageData) else {
            throw Abort(.badRequest)
        }

        // Do what you want with your image
    })
}

我的表格是这样的:

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="imageData" />
    <input type="submit" value="Send" />
</form>

为了 req.content.decode(Question.self) 工作,您的模型必须符合 Content 协议,该协议是 Codable + 其他 encoding/decoding 东西的 Vapor 封装。

您是否将其添加到您的 Question 模型中?

类似的东西:

extension Question: Content {}

这使用多部分形式的自动解码:

router.get("upload") {
    request -> Future<View> in
    return try request.view().render("upload")
}

struct ExampleUpload: Content {
    let document: File
}

// this saves the file into a Question
router.post(ExampleUpload.self, at:"upload") {
    request, upload -> Future<HTTPResponseStatus> in
    let question = try Question()
    question.imageData = upload.document.data
    question.imageName = upload.document.filename
    return question.save(on:request).transform(to: HTTPResponseStatus.ok)
}

upload.leaf 文件是:

<form method="POST" enctype="multipart/form-data">
<input type="file" name="document" />
<input type="submit" value="Send" />
</form>

使用类型 File 可以访问上传文件的本地文件名以及文件数据。如果将其余的问题字段添加到 ExampleUpload 结构中,则可以使用路由来捕获整个表单的字段。