Search code examples
swiftxcodealamofiremultipart

send a picture with alamofire /mulipart


how can I send a picture with multipart? I tested this code but the server saying that : Object reference not set to an instance of an object. where is the problem? or any one can suggest a new code that I can try... I'm working on it for three days and I got same result. parmeters is just these two ids and the file. where is the problem?

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[String : Any]) {
    print("control")
    var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    tempImage = resizeImage(image: tempImage, newWidth: 300)!

    let data = UIImageJPEGRepresentation(tempImage, 0.7)
    updateProfile(imageData: data)

}

  func updateProfile(imageData:Data?) {
        print(imageData)
        var parameters : [String:String] = [:]
        parameters["id"] = "2011"
        parameters["contactid"] = "2030"
    print(parameters)
        let url = "https://madyar.org/MessageAPI/PostFileMessage"
        print(url)

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in parameters {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }

            if let data = imageData {
                multipartFormData.append(data, withName: "image_url", fileName: "image.jpeg", mimeType: "image/jpeg")
            }

        }, usingThreshold: UInt64.init(), to: url, method: .post) { (result) in
            switch result{
            case .success(let upload, _, _):
                upload.responseString { response in
                    print("Succesfully uploaded  = \(response)")
                    if let err = response.error{

                        print(err)
                        return
                    }

                }
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")

            }
        }

}

Solution

  • Use this code it will work fine. with this you can also check upload progress.

     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
    
            uploadImage(image: pickedImage!)
    
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func uploadImage(image : UIImage){
        var parameters : [String:String] = [:]
        parameters["id"] = "2011"
        parameters["contactid"] = "2030"
        print(parameters)
    
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(image, 0.2)!, withName: "image_url", fileName: "image.jpeg", mimeType: "image/jpeg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to:"https://madyar.org/MessageAPI/PostFileMessage")
        { (result) in
            switch result {
            case .success(let upload, _, _):
    
                upload.uploadProgress(closure: { (progress) in
                    print(progress)
                })
    
                upload.responseJSON { response in
                    print(response)
                }
    
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }