如何在Alamofire中使用multipart在多个图像阵列中上传多个图像?

时间:2018-05-30 14:24:45

标签: ios swift alamofire multipartform-data swift4.1

我在使用Alamofire中的多部分在多个图像阵列中上传多个图像时遇到问题。 谁能帮我?在此先感谢!!

我正在使用以下代码

let fileParameters = ["array_1": images1Array,
                      "array_2": images2Array]

func requestUpload(files: [String: Any]? = nil) {

Alamofire.upload( multipartFormData: { multipartFormData in
        if let files = files {
            for (key, value) in files {
                if let images = value as? [UIImage] {
                    for (index, image) in images.enumerated() {
                        let imageData = UIImageJPEGRepresentation(image, 1.0)
                        multipartFormData.append(imageData!, withName: "\(index)", fileName: "\(index).jpg", mimeType: "image/jpg")
                    }
                }
            }
        }
}, to: path , method: .post , headers: request.headers,
          encodingCompletion: { encodingResult in

            self.validatedData(of: encodingResult, handler: { (result, error) in
                handler(result, error)
            })
        })
}

所以我想知道如何在特定键中附加多个图像。

服务器请求如下:

"array1":[
     {
        product_image: img1.jpg
     },
     {
        product_image: img2.jpg
     }
  ],
  "array2":[
     {
        product_image: img3.jpg
     }
  ]

2 个答案:

答案 0 :(得分:1)

我希望这会有用

制作你的密钥数组类型: -

var tmp = new DatePipe('en-Us').transform(this.today, 'dd:MM:yyyy hh-mm-ss');

使你的循环以递增的顺序创建索引值,如0,1,2,3 ..... N

答案 1 :(得分:1)

使用flatmap连接imagesArrays并循环显示图像。

let allImages = fileParameters.values.flatMap{$0}

allImages.enumerated().forEach {    
   multipartFormData.append(UIImagePNGRepresentation($1.values.first), withName: "product_image\($0)", fileName: "\($0).jpg", mimeType: "image/jpg")
}