Vapor upload multiple files at once

若如初见. 提交于 2019-12-04 07:35:17

Example below works well, tested multiple times already 🙂

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

btw also you could declare your payload exactly in the function params

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

the only difference is in declaring endpoint function on router

router.post("upload", use: myUpload)

vs

router.post(MyPayload.self, at: "upload", use: myUpload)

Then in Postman upload your files like this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!