如何使用Swift 4.2通过POST调用将带有一些额外参数的图像数据上传到服务器?

时间:2019-03-11 09:14:09

标签: ios swift

我的情况是,我尝试使用parameters调用将一些Image DataPOST发送到服务器。在这里,我需要将代码Parameters更新为Body请求,因为Image base64产生了巨大的data字符串,因此我们不能随其发送长整数数据。请更新打击代码,如何将图像和额外的parameters上传到Server

apiPath = "https://............com/api/new_line?country=\(get_countryID ?? "unknown")&attachment=\("sample.png")&user_id=\(userid ?? "unknown")"

         if let encodeString = apiPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
            let url = URL(string: encodeString) {

            let session = URLSession.shared
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue(access_key, forHTTPHeaderField: "access-key")
            request.addValue(auth_token!, forHTTPHeaderField: "auth-token")
            request.timeoutInterval = 10

            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

                guard error == nil else {return}
                guard let data = data else {return}

                do {
                    //MARK: Create json object from data
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)

                        // MARK: Validate status code
                        let status_code : Int = json["status"]! as! Int
                        let status_message : String = json["message"]! as! String

                        if (status_code != 200) {
                            print("ERROR:\(String(describing: status_code))")
                            DispatchQueue.main.async {
                                self.showMessageToUser(messageStr: status_message)
                            }

                        } else {

                            DispatchQueue.main.async {

                                // Show Success Alert View Controller
                                if self.tfData != "" {  // Call Update

                                    self.apistatus(message:Updated Successfully!")

                                } else {

                                    self.apistatus(message:"Submitted Successfully!")
                                }
                            }
                        }
                    }
                } catch let error {
                    print(error.localizedDescription)
                }
            })
            task.resume()
            }

2 个答案:

答案 0 :(得分:0)

您可以尝试如下使用Alamofire(https://github.com/Alamofire/Alamofire)。

Alamofire.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(photoData, withName: "photoId", fileName: "photoId.png", mimeType: "image/png")
            for (key,value) in params { //params is a dictionary of values you wish to upload
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }   
        },
        to: URL(string : urlString)!,
        method: .post,
        headers: getContentHeader(),
        encodingCompletion: { encodingResult in

            switch encodingResult {

            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if response.response?.statusCode == 200 {
                        print("Success")
                    } else {
                        print("Failure")    
                    }
                }

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

答案 1 :(得分:0)

// Iam use alamofire Method
   func sendIMAGeAndParams(urlString:String,imageData:[String:[Data]],header: String,params:[String:AnyObject], success: @escaping (AnyObject) -> Void,failure: @escaping(Error)  -> Void) {
            let param = ["" : ""]
            let url = try! URLRequest.init(url: urlString, method: .post, headers: nil)

            Alamofire.upload(multipartFormData: { (formdata) in
                for (key, value) in params {

                    formdata.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)    
                }

                for (key,value) in imageData{
                    for item in value{
                        formdata.append(item, withName: key, fileName: "image.jpeg", mimeType: "image/jpeg")
                    }
                }

            }, with: url) { (encodingResult) in
                switch encodingResult{
                case .success(let upload,_,_):
                    upload.responseJSON(completionHandler: { (response) in
                        switch response.result{
                        case .success(_):
                            if (response.response?.statusCode == 200){
                                if let value = response.result.value {
                                    success(value as AnyObject)
                                    print(value)
                                }
                            }
                            else{
                                let value = response.result.value as? [String:Any]
                                print(value as Any)
                            }
                            break
                        case .failure(let error):
                            print(error)
                            break
                        }
                    })
                    break
                case .failure(let error):
                    print(error)
                    break
                }
            }

    }