Alamofire 4 and Swift 3 Image upload with other parameters

試著忘記壹切 提交于 2019-12-13 17:52:59

问题


I'm trying to upload a image with other parameters the issue occurs when my one of my parameters have a datatype of [String]. The array will be empty on the server side.:/ With other datatypes everything works well.

  self.manager.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: imgKey, fileName: "image.jpg", mimeType: "image/jpg")

                for (key, value) in params {
                    multipartFormData.append(serialize(value)!, withName: key)
                }

            },
            to: path,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint("SUCCESS RESPONSE: \(response)")
                    }
                case .failure(let encodingError):
                    print("ERROR RESPONSE: \(encodingError)")

                }
            }
        )

func serialize(_ value: Any) -> Data? {
        if JSONSerialization.isValidJSONObject(value) {
            return try? JSONSerialization.data(withJSONObject: value, options: [])
        }
        else {
            return String(describing: value).data(using: .utf8)
        }
    }

My Params are [String: Any]

What I'm exactly doing wrong? :(

The problem it's definitely on the client side. Everything works fine when I'm using Postman or other HTTP Services


回答1:


Alamofire.upload(multipartFormData: { multipartFormData in
    var index = 1
    for image in imageArray {
        let imageData: Data = (UIImageJPEGRepresentation(image, 1.0) as Data?)!

        multipartFormData.append(imageData, withName: "home-\(index)", fileName: "home-\(index)", mimeType: "image/jpeg")

        index += 1
    }
    }, with: requestName, encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print("Image(s) Uploaded successfully:\(response)")
            }
        case .failure(let encodingError):
            print("encodingError:\(encodingError)")
        }
})



回答2:


I know the question guidelines say not to ask for clarification but I don't have enough rep to comment yet.

How are you accessing the array on the server? How did you send the array with other services?

More importantly, it looks like params is a [String:String]. How are you adding a [String] value to that? Are you serializing it?




回答3:


I use this code to upload as many images and parameters I want, I hope it helps

Alamofire.upload(multipartFormData: { (MultipartFormData) in
            var secondCounter = 0
            for data in imageDataArray {
                print(imageNamesArray[secondCounter])
                MultipartFormData.append(data, withName: imageNamesArray[secondCounter], fileName: imageNamesArray[secondCounter] + "myImage.png", mimeType: "application/octed-stream")
                secondCounter = secondCounter + 1
            }
            contentDict = parameters as! [String : String]
            for (key, value) in contentDict {
                MultipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
            }, to: url, method: .post, headers: nil, encodingCompletion: { (result) in
                switch result {
                case .success(let upload, _, _):
                    upload.responseJSON(completionHandler: { (dataResponse) in
                        if dataResponse.result.error != nil {
                            completion(nil, nil, dataResponse.result.error as? NSError, false)
                        }
                        else {
                            print(dataResponse.result.value)
                            completion(nil, nil, nil, true)
                        }
                    })
                case .failure(let encodingError):
                    print(encodingError)
                    completion(nil, nil, nil, false)
                }

Ignore the prints Lol




回答4:


It's working for me right know. The solution is really simple as you using MultipartFormData to uploading files you need to take a look to RFC 2388. To upload a array you need this format which is really important. For example if you want to upload a array of strings you need to include brackets to your key!!!

Value: "234234"  Key: keyname[]

You need to append the data in a loop again and again.

For example take a look of this swift code using Alamofire.

for (key, value) in params {
            if JSONSerialization.isValidJSONObject(value) {
                let array = value as! [String]

                for string in array {
                    if let stringData = string.data(using: .utf8) {
                        multipartFormData.append(stringData, withName: key+"[]")
                    }
                }

            } else {
                multipartFormData.append(String(describing: value).data(using: .utf8)!, withName: key)
            }
        }

If the variable is a valid JSONObject I append the data to my array. Again don't forget to include the [] brackets to your keyword.



来源:https://stackoverflow.com/questions/41021802/alamofire-4-and-swift-3-image-upload-with-other-parameters

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