具有请求参数和标头的分段上传(Alamofire)

时间:2019-07-13 05:12:28

标签: swift file-upload alamofire multipartform-data image-uploading

我正在尝试在服务器上上传照片,我必须设置请求标头和参数。

在邮递员中,请求如下图所示: enter image description here

我不知道如何设置第一键“扫描”。 我试图为扫描键设置图像本地路径,图像大小,但没有结果。

我尝试过将图像上传到服务器上:

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

        if let data = imageData{
            multipartFormData.append(data,  withName: "image", fileName: "image.png", mimeType: "image/png")
        }   
    }, usingThreshold: UInt64.init(), to: ApiClientURLs.photo, method: .post, headers: headers) { (result) in
        switch result {
        case .success(let upload, _, _):

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

            upload.responseJSON { response in
                //self.delegate?.showSuccessAlert()
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                //                        self.showSuccesAlert()
                //self.removeImage("frame", fileExtension: "txt")
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }

        case .failure(let encodingError):
            //self.delegate?.showFailAlert()
            print(encodingError)
        }
    }

服务器端的同事告诉我,分段上传存在问题,并向我发送了此错误消息:

default message [scan]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'scan'

标题和参数请求如下:

      let headers: HTTPHeaders = [
        "Content-type" : "multipart/form-data",
        "X-Email"      : decodedLoginModel.email ?? "",
        "Token"        : decodedLoginModel.jwt ?? ""]    

    var params: [String: Any] =  [
        //"scan" : imagePath
        "contact_email": contact_email_switch,
        "contact_mail": contact_mail_switch,
        "contact_phone": contact_phone_switch,
        "contact_sms": contact_sms_switch,
        "required_id": Int.random(in:1111...1999) ]

您能帮我修复上载吗?

1 个答案:

答案 0 :(得分:0)

尝试一下。...

///PARAM and URL
let strURL = “(Your Base URL)api-profile/updateProfile"
let  headersdata = ["Accept":"application/json","content-type": "application/x-www-form-urlencoded","X-Auth-Token": tokon,"X-Email":email]

let postString = ["userId": user_id,"api_version":Constants.api_version,"mobile_no":"9876543210","first_name":lbl_fname.text!,"last_name":lbl_lname.text!,"email":lbl_email.text!,"password":lbl_pass.text!,"sms_notify":smsnoti,"email_notify":emailnoti,"phone_notify":mobilenoti,"is_online":isOnline,"userImage":""] as [String : AnyObject]

////Alamofire Method
        let fileData = selectedImg!.jpegData(compressionQuality: 0.5)

        let URL2 = try! URLRequest(url: "\(strURL)", method: .post, headers: headersdata)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append((fileData)!, withName: "userImage", fileName: "fileImage.jpg", mimeType: "text/plain")

            for (key, value) in postString {
                print(key,value)

                if value is Bool {
                    multipartFormData.append(("\(value)").data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
                }
                else
                {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }


            }
        }, with: URL2 , encodingCompletion: { (result) in


            switch result {
            case .success(let upload, _, _):
                print("s")
                upload.responseJSON {
                    response in
                    if let JSON = response.result.value as? [String : Any]{

                        print(JSON)

                        let messageString = JSON["message"] as? String
                        // use the JSON
                        ACProgressHUD.shared.hideHUD()

                        if JSON["status"]as! Int == 1{
                            //Success
                            print("Success")

                            //self.view.makeToast(messageString!)
                            //Success
                            let resmsg = JSON["message"]! as! String


                            let tempDict = JSON["user_data"]! as! Dictionary<String,Any>


                            print(tempDict)

                            UserDefaults.standard.set(tempDict["image"]!, forKey: "image")

                            self.view.makeToast(resmsg)


                        }else
                        {
                            print("Fail")
                        }
                        print(JSON)
                    }else {
                        //error hanlding
                    }

                    ACProgressHUD.shared.hideHUD()
                }
            case .failure(let encodingError):
                print("F , \(encodingError)")
                ACProgressHUD.shared.hideHUD()

            }
        }
        )
    }

这对我来说就是UPDATE PROFILE。