Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

ios - How to upload image data with some extra parameters to server via POST call using Swift 4.2?

My scenario, I am trying to send some parameters with Image Data to server using POST call. Here, I need to update my code Parameters to Body request, because Image base64 string huge data producing so we cant send long lenth data with it. Please update blow code how to upload image and extra parameters to 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()
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try using Alamofire (https://github.com/Alamofire/Alamofire) as below.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...