以下示例运行良好,已经多次测试馃馃
struct MyPayload: Content { var somefiles: [File] } func myUpload(_ req: Request) -> Future<HTTPStatus> { let user: User = try req.requireAuthenticated() return try req.content.decode(MyPayload.self).flatMap { payload in let workDir = DirectoryConfig.detect().workDir return payload.somefiles.map { file in let url = URL(fileURLWithPath: workDir + localImageStorage + file.filename) try file.data.write(to: url) return try Image(userID: user.requireID(), url: imageStorage + file.filename, filename: file.filename).save(on: req).transform(to: ()) }.flatten(on: req).transform(to: .ok) } }
顺便说一句,你也可以在函数参数中完全声明你的有效载荷
func myUpload(_ req: Request, _ payload: MyPayload) -> Future<HTTPStatus> { let user: User = try req.requireAuthenticated() let workDir = DirectoryConfig.detect().workDir return payload.somefiles.map { file in let url = URL(fileURLWithPath: workDir + localImageStorage + file.filename) try file.data.write(to: url) return try Image(userID: user.requireID(), url: imageStorage + file.filename, filename: file.filename).save(on: req).transform(to: ()) }.flatten(on: req).transform(to: .ok) }
唯一的区别是在路由器上声明端点功能
router.post("upload", use: myUpload)
VS
router.post(MyPayload.self, at: "upload", use: myUpload)
然后在邮递员上传这样的文件