How to append array in multipart form data with Alamofire?

三世轮回 提交于 2020-01-15 09:33:10

问题


I am uploading image with multipart form data using Alamofire but getting some problem while i am passing an array as parameter.

As per request i need to pass all data into letter. Here is how i am doing.

    let data = try! JSONSerialization.data(withJSONObject: arrSelectedRecipientsID, options: .prettyPrinted)
    let jsonString = String(data: data, encoding: .utf8)!

    let paramArr : [String : Any] = [
        "message" : txtvwMessage.text!,
        "status": "draft",
        "recipient_ids": jsonString
    ]

    let parameter  : [String : Any] = ["letter" : paramArr]

    let accesstoken = Utilities.retriveValueFromDefault(forKey: UDKey.kUserAuthentication_Token) as String
    let client = Utilities.retriveValueFromDefault(forKey: UDKey.kUserClient) as String
    let uid = Utilities.retriveValueFromDefault(forKey: UDKey.kUserUID) as String


    let headersInfo : HTTPHeaders = [ "Content-Type" : "multipart/form-data",
                                      "Accept" : "application/json",
                                      "access-token" : accesstoken,
                                      "client" : client,
                                      "uid" : uid
    ]


    fileUploadWithParameter(Constant.ServerAPI.kPostLetters, images: letterImage, header: headersInfo, parameters: parameter, success: { (response) in

        print(response)
    }) { (progress) in


    }

Here is Alamofire request method.

func fileUploadWithParameter(_ url: String,images:NSMutableArray,header : [String : String], parameters: [String:Any], success:@escaping (NSDictionary)->(),progressHandler:@escaping(_ progress: Double)->Void) {

    Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<images.count {

            let rotatedImage = images[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }
        }
        for (key, value) in parameters {

            //multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
            let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
            multipartFormData.append(paramsData, withName: key)

        }

    }, to: url,
       method:.post,
       headers:header) { (result) in
        print("\n\n\nRequest URL :- \(url)\nParameters :- \(parameters)")
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in

                if response.error != nil {
                    print("Error :- \((response.error?.localizedDescription)!)\n\n\n")
                }
                if let jsonDict = response.result.value as? NSDictionary {
                    print("Response :- \(jsonDict)\n\n\n")

                } else {
                    print("Error :- \(Constant.ErrorMessage.kCommanError)\n\n\n")

                }
            }
        case .failure(let encodingError):
            print("Error :- \(encodingError.localizedDescription)\n\n\n")

        }

    }
}

Postman works well so can someone please help me where i am doing wrong.

API expected The proper json should be

 {
   "letter":
          {
            "message": "Type your message here...!!!",
            "recipient_ids": [183, 184],
            "status": "draft"
          }
 }

API is in ruby on rails and it says i am sending string. Please help me to find out what is issue.


回答1:


Finally get it done with separate append in request. Here is how you can pass an array in multipart form data request.

Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<self.letterImage.count {

            let rotatedImage = self.letterImage[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos][]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }

        }

        multipartFormData.append("\(message)".data(using: String.Encoding.utf8)!, withName: "letter[message]")
        multipartFormData.append("draft".data(using: String.Encoding.utf8)!, withName: "letter[status]")

        for (_,value) in self.arrSelectedRecipientsID.enumerated() {

            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "letter[recipient_ids][]")
        }

    }



回答2:


you can append array of like below

for image attachments

for Attachment in Attachments
{
    if let pic = Attachment{
       let randome = arc4random()
       let data = UIImageJPEGRepresentation(pic, 0.8)
       MultipartFormData.append(data!, withName: "letter[photos][]", fileName: "randome\(randome).jpg", mimeType: "image/jpg")
                }
}

for parameters

for (key,value) in params
 {
   MultipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "\(key)")
 }



回答3:


Jus need to change only given line of code:

  for (key, value) in parameters {
            if key == "letter" {
                let arrData =  try! JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                multipartFormData.append(arrData, withName: key as String)
            }
            else {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
        }

Rest will be the same.

your method in updated form: func fileUploadWithParameter(_ url: String,images:NSMutableArray,header : [String : String], parameters: [String:Any], success:@escaping (NSDictionary)->(),progressHandler:@escaping(_ progress: Double)->Void) {

    Alamofire.upload(multipartFormData: { multipartFormData in
        for i in 0..<images.count {

            let rotatedImage = images[i] as! UIImage

            if let imgData = UIImageJPEGRepresentation(rotatedImage, 0.8) {
                multipartFormData.append(imgData, withName: "letter[photos]",fileName: "0\(i).jpg", mimeType: "image/jpg")
            }
        }
        for (key, value) in parameters {

            //multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key )
            let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
            multipartFormData.append(paramsData, withName: key)

        }

        for (key, value) in parameters {
            if key == "letter" {
                let arrData =  try! JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                multipartFormData.append(arrData, withName: key as String)
            }
            else {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
        }

    }, to: url,
       method:.post,
       headers:header) { (result) in
        print("\n\n\nRequest URL :- \(url)\nParameters :- \(parameters)")
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in

                if response.error != nil {
                    print("Error :- \((response.error?.localizedDescription)!)\n\n\n")
                }
                if let jsonDict = response.result.value as? NSDictionary {
                    print("Response :- \(jsonDict)\n\n\n")

                } else {
                    //print("Error :- \(Constant.ErrorMessage.kCommanError)\n\n\n")
                    print("Errfdc")
                }
            }
        case .failure(let encodingError):
            print("Error :- \(encodingError.localizedDescription)\n\n\n")

        }

    }
}


来源:https://stackoverflow.com/questions/51260292/how-to-append-array-in-multipart-form-data-with-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!