首页 > 解决方案 > 如何在 Alamofire 中使用 multipart 上传多个图像数组中的多个图像?

问题描述

我在使用 Alamofire 中的 multipart 上传多个图像数组中的多个图像时遇到问题。谁能帮我?提前致谢!!

我正在使用以下代码

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

标签: iosswiftalamofiremultipartform-dataswift4.1

解决方案


我希望这会奏效

使您的键数组类型:-

 multipartFormData.append(imageData!, withName: "product_image[\(index)]", fileName: "\(index).jpg", mimeType: "image/jpg")

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


推荐阅读