使用PostgreSQL在Vapor 3中上传图像

Kri*_*oen 11 multipartform-data swift vapor leaf

我正在关注这些家伙Martin Lasek Tutorials,现在我正在"图片上传".似乎没人能回答"如何上传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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和型号:

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
}
Run Code Online (Sandbox Code Playgroud)

}

和叶子模板:

<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>
Run Code Online (Sandbox Code Playgroud)

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

但是我怎么去那里?

Nic*_*ick 6

这使用多部分表单的自动解码:

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)
}
Run Code Online (Sandbox Code Playgroud)

upload.leaf文件是:

<form method="POST" enctype="multipart/form-data">
<input type="file" name="document" />
<input type="submit" value="Send" />
</form>
Run Code Online (Sandbox Code Playgroud)

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