简体   繁体   中英

Upload Image file from app Swift

I am trying to upload image file to my server. Below screen shows call through postman.

With KEY : "image" and Value : 123.png [image file] in form-data Body.

在此处输入图片说明

I want to implement the same in my app using swift. I tried different solution but dint find a proper solution.

I am a selecting image with help of UIImagePicker:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
            {
                let image = info[UIImagePickerControllerOriginalImage] as? UIImage
                self.dismiss(animated: true, completion: nil)
                uploadImage(image: image!, url: "profile_image/")
            }

I call uploadImage function to upload image.

func uploadImage(image: UIImage, url: String) {
        let urlString = "http://example.com/path/"+url
        guard let url = URL(string: urlString) else { return }
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        let token = UserDefaults.standard.object(forKey: "token") as? String
        request.addValue("Token "+token!, forHTTPHeaderField: "Authorization")
        let imageData = UIImagePNGRepresentation(image)!.base64EncodedData()
        //let postString = "image=\(imageData))"
        //request.httpBody = postString.data(using: .utf8)

    let imgDict = ["image": imageData]

    do {
        let jsonBody = try JSONEncoder().encode(imgDict)
        print(jsonBody)
        request.httpBody = jsonBody
    } catch let jsonError {
        print(" Parsing Error: "+jsonError.localizedDescription)
    }

        URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if error != nil {
                print("Image upload API Error: "+error!.localizedDescription)
            }
            guard let data = data else { return }
            do {
                print(data)
                let responseData = try JSONDecoder().decode(BasicResponseParameter.self, from: data)
                print(responseData)

                if responseData.success {
                    print("Image uploaded")
                }
                else {
                    print("Image upload API Failed : "+responseData.message!)
                    DispatchQueue.main.async(execute: {
                        popAlert(title: "FAILED", message: responseData.message!, owner:self)
                    })
                }
            } catch let jsonError {
                print("Image upload API JSON Error :"+jsonError.localizedDescription)
            }
            }.resume()
    }

Any help appreciated.

I would suggest that you encode (when sending the image to your server) and decode (when querying the image back) your image into base64 format

To encode

let img = /// this is your image 
let encodedString =   UIImagePNGRepresentation(img)?.base64EncodedString() 

To Decode:

let data_from_response = /// from your response 
let decodeData = Data(base64Encoded: data_from)

Since you are sending a dictionary over your request body, you will need to convert your dictionary to a json

guard let imgDataString = String.init(data: encodedString, encoding: String.Encoding.utf8) else { return } 

let imgDict = ["image": imgDataString ] 

let jsonData = try! JSONSerialization.data(withJSONObject: imgDict, options: .prettyPrinted)

request.httpBody = jsonData 

Side Note Avoid implicit optional unwrapping meaning ! , either use if let or guard statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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