使用alamofire上传带参数的图像

时间:2019-02-05 06:18:15

标签: ios swift4

我正在尝试使用alamofire将图像和参数一起发送到服务器,但是我不知道天气是否正确。我没有收到响应,得到了类似的错误

{
    errors =     {
        avatar =         (
            "The avatar must be an image.",
            "The avatar must be a file of type: jpeg, jpg, png."
        );
        city =         (
            "The city may not be greater than 50 characters."
        );
        state =         (
            "The state may not be greater than 50 characters."
        );
    };
    message = "Invalid input.";
    status = 400;
    success = 0;
}

如果有人帮助我,那就太好了。 预先感谢

    let imageobj = img.image!
    let data = imageobj.pngData()


    let acce:String = UserDefaults.standard.string(forKey: "access")!
    print(acce)

    let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)"]

    postParameters = ["name":username,"password":pass,"password_confirmation":confirmpass,"city":newcity,"state":newstate,"address":addre]
    print(postParameters)

    let userData:Data = try! JSONSerialization.data(withJSONObject: postParameters)


    Alamofire.upload(multipartFormData: { (multiFoormData) in
        multiFoormData.append(userData, withName: "name")
        multiFoormData.append(userData, withName: "password")
        multiFoormData.append(userData, withName: "password_confirmation")
        multiFoormData.append(userData, withName: "city")
        multiFoormData.append(userData, withName: "state")
        multiFoormData.append(userData, withName: "address")
        multiFoormData.append(userData, withName: "avatar", mimeType: "image/png")
    }, to: Constants.Userdetailsapi,method:.post,
       headers:headers,
       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
                print(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })

2 个答案:

答案 0 :(得分:0)

if let  img = info[UIImagePickerControllerOriginalImage] as? UIImage{

        self.imgProfileImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        let imgData = UIImageJPEGRepresentation(img, 0.5)!

        let parameters = ["service_type":"que_update_profile",
                          "user_id":UserDefaults.standard.string(forKey: "user_id")  ?? "",
                          "que_m_firstname":self.txtFirstName.text!,
                          "que_m_lastname":self.txtLastName.text!,
                          "que_m_birthdate":self.lblDateofBirth.text!,
                          "que_m_gender":"\(self.selectedGender)",
                          "que_m_phone":self.txtPhone.text!,
                          "que_m_address":self.txtAddress.text!] as [String : Any] //Optional for extra parameter

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "profile_imgname",fileName: "ProfilePic_\(UserDefaults.standard.string(forKey: "user_id") ?? "").jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            } //Optional for extra parameters
        },
                         to:"Server URL Here.")
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value)
                }

            case .failure(let encodingError):
                print(encodingError)
            }
        }

    }
    self.dismiss(animated: true, completion: nil)

答案 1 :(得分:0)

您可以遵循以下结构:

let imageobj = img.image!
let data = imageobj.pngData()

let acce:String = UserDefaults.standard.string(forKey: "access")!
print(acce)

let headers:HTTPHeaders = ["Authorization":"Bearer \(acce)"]
  let ImageData = UIImagePNGRepresentation(imageobj)
  let urlReq = Constants.Userdetailsapi
  let params : Parameters = ["name":username,"password":pass,"password_confirmation":confirmpass,"city":newcity,"state":newstate,"address":addre]

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(ImageData!, withName: "avatar",fileName: "file.jpg", mimeType: "image/jpg")
            for (key, value) in params {// this will loop the 'parameters' value, you can comment this if not needed
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        },
                         to:urlReq)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                     completion("success")
                    }

            case .failure(let encodingError):
                print(encodingError)
                completion("failed")

            }
        }

希望这会起作用。