简体   繁体   English

Vapor一次上传多个文件

[英]Vapor upload multiple files at once

I want to upload multiple images in one POST request. 我想在一个POST请求中上传多个图像。 Currently, the part of my request related to the file upload is taking one file and looks like this: 目前,我的文件上传请求部分是一个文件,如下所示:

return try req.content.decode(File.self).flatMap(to: Image.self) { (file) in
    try file.data.write(to: URL(fileURLWithPath: DirectoryConfig.detect().workDir + localImageStorage + file.filename))
    return try Image(userID: user.requireID(), url: imageStorage + file.filename, filename: file.filename).save(on: req)
}

This works just fine. 这很好用。 Now, I tried to change .decode(File.self) to .decode([File].self) , and do a loop for all files. 现在,我尝试将.decode(File.self)更改为.decode([File].self) ,并为所有文件执行循环。
When trying to upload images using the data[] parameter in Postman, I get the following error: 尝试使用Postman中的data[]参数上传图像时,出现以下错误:

Nested form-data decoding is not supported. 不支持嵌套表单数据解码。

How do I solve this? 我该如何解决这个问题?

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 VS

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

Then in Postman upload your files like this 然后在邮递员上传这样的文件 PostmanMultipleFiles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM