2016-07-17 6 views
0

Alamofireを使用してサーバーリクエストを作成しようとしています。 ファイルとしてパラメータを送信する必要があります。AlamoFireを使用してPOSTリクエストでjpegファイルをパラメータとして送信する方法

var parameters: [String: AnyObject] = [:] 
    parameters["PAYLOAD"] = payloadString // String 
    parameters["FINGERPRINT"] = deviceUniqueIdString // String 

私はUIImageJPEGRepresentationを(使用したNSDataに変換することをUIImageを持っている)

let imageData = UIImageJPEGRepresentation(myUIImage, 1.0) 
    parameters["IMAGE_FILE"] = imageData 

その後、私がリクエストを送信するためにAlamofireを使用します。

Alamofire.request(.POST, apiURL, parameters: parameters).responseJSON { response in 

    } 

とき私はこの要求は動作しますペイロードと指紋のパラメータを送信しますが、 "IMAGE_FILE"パラメータを含めると、サーバはエラーを返します。

UIImageはどのように送信する必要がありますか?

答えて

1

@Fujiaの回答に加えて、私は例を追加したいと思います。

func WasperEntrepriseImageUploadCall(method: Alamofire.Method, imageData: NSData, parameters: [String: AnyObject]?, headers: [String: String]?, urlToPost: String, 
    progressionHandler: (bytesWritten: Int, totalBytesWritten: Int, totalBytesExpected: Int) ->(), 
    completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject,NSError>, NSData?) ->()){ 

    Alamofire.upload(
     method, urlToPost, headers: headers, 
     multipartFormData: { multipartFormData in 
      multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "doesntmatter", mimeType: "image/png") 

      if let params = parameters{ 
       for (key, value) in params { 
        multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) 
       } 
      } 
     }, 
     encodingCompletion: { encodingResult in 
      switch encodingResult { 
      case .Success(let upload, _, _): 

       upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in 
        progressionHandler(bytesWritten: Int(bytesWritten), totalBytesWritten: Int(totalBytesWritten), totalBytesExpected: Int(totalBytesExpectedToWrite)) 
       } 
       upload.response { response in 
              }.validate() 
        .responseJSON { response in 

         if let resp = response.response{ 
          print(resp.statusCode) 
          print(response.result.value) // result of response serialization       
         } 
         completionHandler(response.request,response.response,response.result, response.data) 
       } 
      case .Failure(let encodingError): 
       print(encodingError) 
      } 
     } 
    ) 
} 

最善の解決策はないが、それはあなたの頭のスタートを与える必要があります。これは私がPNGファイルを投稿するために、最近使用されている方法です。私が信じているSwiftyJSONとAlamofire 3.0の両方が必要です。便利な進行状況のための補完ハンドラを提供します。ここで詳細な回答を見つけられるはずです:Uploading file with parameters using Alamofire

1

Alamofire.requestの代わりにAlamofire.upload(_:multipartFormData:encodingMemoryThreshold:encodingCompletion:)を使用してください。 mutipartクロージャーにパラメータ(文字列とデータの両方を含む)を追加することができます。

関連する問題