使用alamofire multipart上传图像数组

时间:2019-02-04 11:26:49

标签: swift alamofire multipart

我使用alamofire分段将图像阵列上传到服务器,它仅上传第一张图像(阵列计数的次数),而不上传其余图像,我检查从图像选择器获取图像到将图像附加到图像之前和之后的所有操作多部分

extension profileViewController{
@objc private func UploadImage()
{

    let headers = ["Authorization": "Bearer \(AuthService.instance.Auth_Token)"]
    Alamofire.upload(multipartFormData: { multipartFormData in
        if self.ImageArray?.isEmpty == false{
            for (index, image) in self.ImageArray!.enumerated(){
                print(index)
                var imageData = image.jpegData(compressionQuality: 0.6)
                print(imageData)
                multipartFormData.append(imageData!, withName: "photos[]", fileName: "\(self.RandomString(length: 10)).jpeg",mimeType: "image/jpeg")
                print(imageData)
                imageData?.removeAll()
            }
        }else{
            return
        }
    }, usingThreshold:UInt64.init(),
       to: "http://couponsub.farid.azq1.com/api/save-user-photos"/*upload_imageUrl*/, //URL Here
        method: .post,
        headers: headers, //pass header dictionary here
        encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):
                print("the status code is :")
                upload.uploadProgress(closure: { (progress) in
                    print(progress.fractionCompleted)
                    //self.ProgressBar.progress = CGFloat(Float(progress.fractionCompleted))

                })
                upload.responseJSON { response in
                    if response.result.isSuccess == true{
                        KRProgressHUD.dismiss()
                    }
                    print("the resopnse code is : \(String(describing: response.response?.statusCode))")
                    let json = try! JSON(data: response.data!)
                    print(json)

                }
                break
            case .failure(let encodingError):
                print("the error is  : \(encodingError.localizedDescription)")
                break
            }
    })
}

}

1 个答案:

答案 0 :(得分:0)

func uploadMultipleImages(imagesData:[Data]){
    Alamofire.upload(multipartFormData: { multipartFormData in
        // import image to request
        for imageData in imagesData {
            multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
        }
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: urlString,

       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in

            }
        case .failure(let error):
            print(error)
        }

    })
}