我正在关注这些家伙
Martin Lasek教程,现在我正在“图片上传”.
似乎没有人能回答“如何上传i Vapor 3图像”的问题
似乎没有人能回答“如何上传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>
但我怎么去那里?
这使用多部分表单的自动解码:
原文链接:https://www.f2er.com/swift/319407.htmlrouter.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类型可以访问上载文件的本地文件名以及文件数据.如果将其余的Question字段添加到ExampleUpload结构中,则可以使用该路径捕获整个表单的字段.