使用PostgreSQL在Vapor 3中上传图像 [英] Image Upload in Vapor 3 using PostgreSQL

查看:99
本文介绍了使用PostgreSQL在Vapor 3中上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这些人马丁·拉塞克教程,现在我处于图像上传"状态. 似乎没有人能回答您如何在Vapor 3上上传图片"问题

I'm following this guys Martin Lasek Tutorials and now i'm at "image upload". It seems that no one has the answer to the question "How do you upload images i Vapor 3"

Db连接正常,所有其他值均已保存.

Db connection is ok, all the other values are saved.

这是mye创建方法:

    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
}

}

和Leaf模板:

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

我知道需要一种用于管理文件的方法,并将原始图像字节保存到

I know a method for managing files is needed and the raw image bytes to,

但是我怎么到达那里?

推荐答案

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

This uses automatic decoding of the multi-part form:

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结构中,则可以使用路由捕获整个表单的字段.

Using the type File enables the local filename of the uploaded file to be accessed as well as the file data. If you add in the rest of the Question fields to the ExampleUpload structure, you can use the route to capture the whole form's fields.

这篇关于使用PostgreSQL在Vapor 3中上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆