[英]How to upload files for a model using vapor 3 for an iOS app
我想使用Vapor 3作为我的后端制作iOS应用程序。 我创建的用于表示我的对象的模型包含一些属性,这些属性将是.png和.plist文件等文件。 我无法理解如何使用multipart来获取这些文件并在我发出POST请求时将它们发送到我的模型端点。
我也很困惑我应该将哪些数据类型设置为我的Model类中的那些文件属性。 在“内容”部分下的多部分文档( https://docs.vapor.codes/3.0/multipart/overview/#content )中,他们说要制作一个Struct并将它们的图像设置为Data类型,说你可以使用File类型。 我也看过他们使用String类型的例子。
我希望有人可以澄清我应该将这些属性的数据类型设置为什么以及如何在我的控制器/ ModelController中上传这些文件,我在其中执行保存并在我的启动(路由器:路由器)函数中调用.post()
我已经查看了Multipart蒸汽文档并阅读了这些stackoverflow帖子,但是当我尝试使用post方法时仍然无法理解我应该做什么: - Vapor一次上传多个文件 - 如何使用Vapor处理多部分请求3 - 使用PostgreSQL在Vapor 3中上传图像
这是我的模型类:
import Vapor
import FluentMySQL
final class AppObject: Codable {
var id: Int?
var plistFile: String // file
var imageFile: String // file
var notes: String
var name: String
init(ipaFile: String, plistFile: String, imageFile: String, notes: String, name: String) {
self.ipaFile = ipaFile
self.plistFile = plistFile
self.imageFile = imageFile
self.notes = notes
self.name = name
}
}
extension AppObject: MySQLModel {}
extension AppObject: Content {}
extension AppObject: Migration {}
extension AppObject: Parameter {}
这是我对上述型号的控制器:
import Vapor
import Fluent
struct AppObjectsController: RouteCollection {
func boot(router: Router) throws {
let appObjectsRoute = router.grouped("api", "apps")
appObjectsRoute.get(use: getAllHandler)
appObjectsRoute.post(AppObject.self, use: createHandler)
}
func getAllHandler(_ req: Request) throws -> Future<[AppObject]> {
return AppObject.query(on: req).all()
}
// what else should I be doing here in order to upload actual files?
func createHandler(_ req: Request, appobject: AppObject) throws -> Future<AppObject> {
return appobject.save(on: req)
}
}
我见过的一些例子涉及上传Web应用程序,他们返回Future <View>,但由于我正在做iOS应用程序,我不知道是否应该返回HTTPResponseStatus或我的模型对象。
请帮助,我尽力说出这个,我是Vapor的新手
模型
final class AppObject: Codable {
var id: Int?
var ipaFile: String // relative path to file in Public dir
var plistFile: String // relative path to file in Public dir
var imageFile: String // relative path to file in Public dir
var notes: String
var name: String
init(ipaFile: String, plistFile: String, imageFile: String, notes: String, name: String) {
self.ipaFile = ipaFile
self.plistFile = plistFile
self.imageFile = imageFile
self.notes = notes
self.name = name
}
}
extension AppObject: MySQLModel {}
extension AppObject: Content {}
extension AppObject: Migration {}
extension AppObject: Parameter {}
调节器
struct AppObjectsController: RouteCollection {
func boot(router: Router) throws {
let appObjectsRoute = router.grouped("api", "apps")
appObjectsRoute.get(use: getAllHandler)
appObjectsRoute.post(PostData.self, use: createHandler)
}
func getAllHandler(_ req: Request) throws -> Future<[AppObject]> {
return AppObject.query(on: req).all()
}
}
extension AppObjectsController {
struct PostData: Content {
let ipaFile, plistFile, imageFile: File
let name, notes: String
}
func createHandler(_ req: Request, payload: PostData) throws -> Future<AppObject> {
let ipaFile = ServerFile(ext: "ipa", folder: .ipa)
let plistFile = ServerFile(ext: "plist", folder: .plist)
let imageFile = ServerFile(ext: "jpg", folder: .image)
let appObject = AppObject(ipaFile: ipaFile.relativePath, plistFile: plistFile.relativePath, imageFile: imageFile.relativePath, notes: payload.notes, name: payload.name)
/// we have to wrap it in transaction
/// to rollback object creating
/// in case if file saving fails
return req.transaction(on: .mysql) { conn in
return appObject.create(on: conn).map { appObject in
try ipaFile.save(with: payload.ipaFile.data)
try plistFile.save(with: payload.plistFile.data)
try imageFile.save(with: payload.imageFile.data)
}
}
}
}
ServerFile结构
struct ServerFile {
enum Folder: String {
case ipa = "ipa"
case plist = "plists"
case image = "images"
case root = ""
}
let file, ext: String
let folder: Folder
init (file: String? = UUID().uuidString, ext: String, folder: Folder? = .root) {
self.file = file
self.ext = ext
self.folder = folder
}
var relativePath: String {
guard folder != .root else { return fileWithExt }
return folder.rawValue + "/" + fileWithExt
}
var fileWithExt: String { return file + "." + ext }
func save(with data: Data) throws {
/// Get path to project's dir
let workDir = DirectoryConfig.detect().workDir
/// Build path to Public folder
let publicDir = workDir.appending("Public")
/// Build path to file folder
let fileFolder = publicDir + "/" + folder.rawValue
/// Create file folder if needed
var isDir : ObjCBool = true
if !FileManager.default.fileExists(atPath: fileFolder, isDirectory: &isDir) {
try FileManager.default.createDirectory(atPath: fileFolder, withIntermediateDirectories: true)
}
let filePath = publicDir + "/" + relativePath
/// Save data into file
try data.write(to: URL(fileURLWithPath: filePath))
}
}
声明AppObject
模型
struct AppObject: Codable {
var id: Int
var ipaFile, plistFile, imageFile: String
var name, notes: String
}
使用CodyFire库,多部分请求非常简单
声明你的端点
import CodyFire
struct AppController: EndpointController {
static var server: ServerURL? = nil
static var endpoint: String = "apps"
}
/// Usually separate file like App+Create.swift
extension AppController {
struct CreateAppRequest: MultipartPayload {
var ipaFile, plistFile, imageFile: Attachment
var name, note: String
public init (ipaFile: Attachment, plistFile: Attachment, imageFile: Attachment, name: String, note: String) {
self.ipaFile = ipaFile
self.plistFile = plistFile
self.imageFile = imageFile
self.name = name
self.note = note
}
}
static func create(_ payload: CreateAppRequest) -> APIRequest<AppObject> {
return request(payload: payload).method(.post)
}
}
然后在某些视图中,控制器尝试在服务器上创建应用程序
/// Replace _ with file data
let ipaFile = Attachment(data: _, fileName: "", mimeType: "ipa")
let plistFile = Attachment(data: _, fileName: "", mimeType: "plist")
let imageFile = Attachment(data: _, fileName: "", mimeType: .jpg)
let payload = AppController.CreateAppRequest(ipaFile: ipaFile,
plistFile: plistFile,
imageFile: imageFile,
name: "something",
note: "something")
AppController.create(payload).onRequestStarted {
/// it calls only if request started properly
/// start showing loading bar
}.onError { error in
let alert = UIAlertController(title: nil, message: error.description, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
self.present(alert, animated: true)
}.onProgress { progress in
/// show progress
}.onSuccess { appObject in
/// show success
/// here you received just created `appObject`
}
就是这样,它只是工作:)
下一个获取AppObject
列表的AppObject
/// Separate file like App+List.swift
extension AppController {
static func list() -> APIRequest<[AppObject]> {
return request()
}
}
然后在视图控制器的某个地方
AppController.list().onSuccess { appObjects in
/// `appObjects` is `[AppObject]`
}
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.