2017-01-10 9 views
2

私はAlamofire 4 with swift 3を使用してユーザプロファイルを更新しています。私はRouterクラスを使っています。私が必要としているのはuplaodで、他のパラメータでは画像です。画像部分をアップロードせずにupdateユーザーの詳細を見ることができます。ios、swift3、Alamofire 4のマルチパートフォームデータを使用して、パラメータとして画像をアップロードする方法

これはpostman

enter image description here

でどのように見えるので、このためurlconvertibleリクエストを作成することも可能です。他のパラメータで画像をアップロードするにはどうすればいいですか? (これは郵便配達でうまくいく)。新しいAlamofireでどうすればいいですか?私は以下のように試しました。

let parameters = [ 
      "profile_image": "swift_file.jpeg" 
     ] 


     Alamofire.upload(multipartFormData: { (multipartFormData) in 
      multipartFormData.append(UIImageJPEGRepresentation(profileImage, 1)!, withName: "file", fileName: "swift_file.jpeg", mimeType: "image/png") 
      for (key, value) in parameters { 
       multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key) 
      } 
     }, to:urltoUpdate) 
     { (result) in 
      switch result { 
      case .success(let upload, _, _): 
       print("the status code is :") 

       upload.uploadProgress(closure: { (progress) in 
        print("something") 
       }) 

       upload.responseJSON { response in 
        print("the resopnse code is : \(response.response?.statusCode)") 
        print("the response is : \(response)") 
       } 
       break 
      case .failure(let encodingError): 
       print("the error is : \(encodingError.localizedDescription)") 
       break 
      } 
     } 

これは正しく機能しませんでした。この部分であなたの助けを願ってください。

答えて

4

あなたはこの必要はありません。

"profile_image": "swift_file.jpeg" 

をとパラメータは次のようになります。

let parameters = [ 
    "firstname": "Bill", 
    "surname": "fox", 
    //...rest of the parameters 
] 

そしてこのwithName: "file"

multipartFormData.append(UIImageJPEGRepresentation(profileImage, 1)!, withName: "file", fileName: "swift_file.jpeg", mimeType: "image/png") 

withName: "profile_image"であるべき:

0123ヘッダと

コード:

let parameters = [ 
    "firstname": "Bill", 
    "surname": "fox", 
    //...rest of the parameters 
] 

let headers = [ 
    "somekey": "somevalue", 
    //...rest of the parameters 
] 

Alamofire.upload(multipartFormData: { (multipartFormData) in 

    multipartFormData.append(UIImageJPEGRepresentation(profileImage, 1)!, withName: "profile_image", fileName: "swift_file.jpeg", mimeType: "image/png") 

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

}, usingThreshold:UInt64.init(), 
    to: "", //URL Here 
    method: .post, 
    headers: headers, //pass header dictionary here 
    encodingCompletion: { (result) in 

    switch result { 
    case .success(let upload, _, _): 
     print("the status code is :") 

     upload.uploadProgress(closure: { (progress) in 
      print("something") 
     }) 

     upload.responseJSON { response in 
      print("the resopnse code is : \(response.response?.statusCode)") 
      print("the response is : \(response)") 
     } 
     break 
    case .failure(let encodingError): 
     print("the error is : \(encodingError.localizedDescription)") 
     break 
    } 
}) 
+0

また、JPEG画像を送信しているので、 'mimeType:" image/png "'についても疑問があります。 –

+0

この 'firstname、latname、例えば ' –

+0

'のような他のパラメータをアップロードするにはどうしたらいいですか?{loopはすでにリクエストボディでパラメータをバインドしています。 –

0

だけNSObjecteファイルにこの方法を置きます。

輸入Alamofire`

class func postImageToUrl(_ serverlink:String,methodname:String,param:NSDictionary,image:UIImage!,withImageName : String,CompletionHandler:@escaping (Bool,NSDictionary) ->()) { 



     print("POST : " + serverlink + methodname + " and Param \(param) ") 

     var fullLink = serverlink 

     if fullLink.characters.count > 0 { 

      fullLink = serverlink + "/" + methodname 
     } 
     else { 

      fullLink = methodname 
     } 

     var imgData = Data() 
     if image != nil { 

      imgData = UIImageJPEGRepresentation(image!, 1.0)! 
     } 

     let notallowchar : CharacterSet = CharacterSet(charactersIn: "").inverted 
     let dateStr:String = "\(Date())" 
     let resultStr:String = (dateStr.components(separatedBy: notallowchar) as NSArray).componentsJoined(by: "") 
     let imagefilename = resultStr + ".jpg" 

     Alamofire.upload(multipartFormData:{ multipartFormData in 
      multipartFormData.append(imgData, withName: withImageName as String, fileName: imagefilename, mimeType: "image/jpeg") 

      for (key, value) in param { 

       //let data = (value as! String).data(using: String.Encoding.utf8)! 
       let data = (value as AnyObject).data(using: String.Encoding.utf8.rawValue) 
       multipartFormData.append(data!, withName: key as! String) 

      } 
     }, 
     usingThreshold:UInt64.init(), 
     to:fullLink, 
     method:.post, 
     headers:[:], 
     encodingCompletion: { encodingResult in 

      switch encodingResult { 

       case .success(let upload, _, _): 

       upload.uploadProgress { progress in // main queue by default 

        print("Upload Progress: \(progress.fractionCompleted)") 
       } 

       upload.responseJSON { response in 

        print(response) 


        if let TempresponseDict:NSDictionary = response.result.value as? NSDictionary { 

         if (TempresponseDict.object(forKey: "response") as? String)?.caseInsensitiveCompare("success") == .orderedSame { 

          CompletionHandler(true, TempresponseDict) 
         } 
         else { 

          var statusCode = response.response?.statusCode 

          if let error = response.result.error as? AFError { 

           statusCode = error._code // statusCode private 

           switch error { 

           case .invalidURL(let url): 
            print("Invalid URL: \(url) - \(error.localizedDescription)") 
           case .parameterEncodingFailed(let reason): 
            print("Parameter encoding failed: \(error.localizedDescription)") 
            print("Failure Reason: \(reason)") 
           case .multipartEncodingFailed(let reason): 
            print("Multipart encoding failed: \(error.localizedDescription)") 
            print("Failure Reason: \(reason)") 
           case .responseValidationFailed(let reason): 
            print("Response validation failed: \(error.localizedDescription)") 
            print("Failure Reason: \(reason)") 

            switch reason { 

            case .dataFileNil, .dataFileReadFailed: 
             print("Downloaded file could not be read") 
            case .missingContentType(let acceptableContentTypes): 
             print("Content Type Missing: \(acceptableContentTypes)") 
            case .unacceptableContentType(let acceptableContentTypes, let responseContentType): 
             print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)") 
            case .unacceptableStatusCode(let code): 
             print("Response status code was unacceptable: \(code)") 
             statusCode = code 
            } 
           case .responseSerializationFailed(let reason): 

            print("Response serialization failed: \(error.localizedDescription)") 
            print("Failure Reason: \(reason)") 
            // statusCode = 3840 ???? maybe.. 
           } 

           print("Underlying error: \(error.underlyingError)") 
          } 
          else if let error = response.result.error as? URLError { 

           print("URLError occurred: \(error)") 
          } 
          else { 

           print("Unknown error: \(response.result.error)") 
          } 

          print("\(statusCode)") // the status code 


          CompletionHandler(false, TempresponseDict) 
         } 
        } 
        else { 

         CompletionHandler(false, NSDictionary()) 
        } 
       } 

       case .failure(let encodingError): 

        print(encodingError) 

        CompletionHandler(false, NSDictionary()) 
      } 
     }) 

} 

2.

yourNSObjectClassName.postImageToUrl(MAIN_LINK, methodname: "MethodName", param: "ParametterInDictionary", image: "UploadImage", withImageName: "ImageParametterString") { (Success, responceOBJ) in 
     if Success == true 
     { 
      print("Your image is uploaded") 
     } 
     else 
     { 
      print("Fail") 
     } 
    } 

し、エラーを表示するには、サーバーのサイトにWebサービスのエラーコードを設定していて、右の成功を取得した後。

関連する問題