我正在关注这些人Martin Lasek教程,现在我在“图像上传”中。 似乎没有人能回答“您如何在Vapor 3上上传图片”问题
Db连接正常,所有其他值均已保存。
这是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>
我知道需要一种用于管理文件的方法,并将原始图像字节保存到
但是我怎么到达那里?
答案 0 :(得分: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)
}
upload.leaf
文件是:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="document" />
<input type="submit" value="Send" />
</form>
使用类型File
可以访问上载文件的本地文件名以及文件数据。如果将其余的“问题”字段添加到ExampleUpload结构中,则可以使用该路由捕获整个表单的字段。
答案 1 :(得分:2)
我已经设法通过以下方法获取图像数据:
UIViewController
我的表单如下:
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
})
}
答案 2 :(得分:2)
为了使req.content.decode(Question.self)
工作,您的模型必须符合Content
协议,即Codable
的蒸气封装+其他编码/解码内容。
您是否将其添加到Question
模型中?
类似的东西:
extension Question: Content {}