alamofire上传的图像数组并不起作用

时间:2016-09-27 16:33:59

标签: ios swift2 alamofire

我需要上传一些带有一些额外文字的图片。我像这样使用了Alamofire:

  let headers = ["Authorization": "Bearer \(userToken)"]
            Alamofire.upload(.POST, "url", headers: headers, multipartFormData: { multipartFormData in

                if let post = post?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
                    multipartFormData.appendBodyPart(data: post, name: "name")
                }
                if let pictures = pictures {
                    for image in pictures {
                        if let imageData = UIImageJPEGRepresentation(image, 1)?.base64EncodedDataWithOptions(.Encoding64CharacterLineLength) {
                            multipartFormData.appendBodyPart(data: imageData, name: "pictures", fileName: "pictures", mimeType: "image/jpeg")
                        }
                    }
                }
                if let pictureText = pictureText?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
                    multipartFormData.appendBodyPart(data: pictureText, name: "picture_text")
                }

                }, encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .Success(let upload, _, _):
                        upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
                            DDLogDebug("Uploading images for status post \(totalBytesWritten) / \(totalBytesExpectedToWrite)")
                        }
                        upload.responseJSON { (response) in
                            let json = response.result.value
                            DDLogDebug("Status post complete \(json)")
                            dispatch_async(dispatch_get_main_queue(),{
                                handler(result: json, error: nil)
                            })
                        }
                    case .Failure(let encodingError):
                        DDLogError("Failed to post: \(encodingError)")
                        handler(result: nil, error: NSError(domain: "failed response", code: 123, userInfo: nil))
                    }
                }
            )
        }

现在的问题是服务器需要一个图像数组,并在第0行的Unknown中给出了多部分/表格数据POST数据中的错误边界。所以上传代码有问题,但我可以&#39 ;弄清楚是什么。在邮递员中,它只是一个数组而且运行正常。我想当我循环浏览图片并给出相同的名称时,它就像一个数组。

1 个答案:

答案 0 :(得分:0)

我忘了将索引添加到文件名这是解决方案

  if let pictures = pictures {
                for (index, image) in pictures.enumerate() {
                    if let imageData = UIImageJPEGRepresentation(image, 1) {
                        multipartFormData.appendBodyPart(data: imageData, name: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
                    }
                }
            }