简体   繁体   English

如何使用 Alamofire 在多部分表单数据中附加数组?

[英]How to append array in multipart form data with Alamofire?

I am uploading image with multipart form data using Alamofire but getting some problem while i am passing an array as parameter.我正在使用 Alamofire 上传带有多部分表单数据的图像,但是在我将数组作为参数传递时遇到了一些问题。 这是邮递员请求

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.这是 Alamofire 请求方法。

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 API 预期正确的 json 应该是

 {
   "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. API 在 ruby​​ on rails 中,它说我正在发送字符串。 Please help me to find out what is issue.请帮我找出问题所在。

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][]")
        }

    }

Jus need to change only given line of code: Jus 只需要更改给定的代码行:

  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")
            
        }
        
    }
}

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)")
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM