2016-12-16 68 views
0

我試圖上傳一個圖像(avatarImage)作爲formData參數類型使用AlamoFire服務器,但我生成一個「數據無法讀取,因爲它不在正確的格式「錯誤每次我嘗試發佈。我不太確定我做錯了什麼。上傳帶參數的圖像(alamofire)

class func createTeamWithAvatar(avatarImage: Image) { 
    let extendedURI = "\(RequestManager.baseURL)" + "\(RequestManager.ClickUpURI.Team.rawValue)" 
    RequestManager.sharedAlamofireManager.upload(multipartFormData: { 
     multipartFormData in 

     //This generates an error: "The data could not be read because it isn’t in the correct format" 
     if let imageData = UIImageJPEGRepresentation(avatarImage, 1) { 
      multipartFormData.append(imageData, withName: "avatar", mimeType: "image/jpeg") 
     } 

     }, to: extendedURI, 
      encodingCompletion: { encodingResult in 
       switch encodingResult { 
       case .success(let upload, _, _): 
        upload.responseJSON { 
         response in 

         if let statusCode = response.response?.statusCode, 
          let response = response.result.value as? Dictionary<String, AnyObject>, 
          let _ = response["id"] as? String 
          , statusCode == 200 
         { 
          completionHandler(response, nil) 
         } else { 
          let responseError = response.result.value as? Dictionary<String, AnyObject> 

          let errorInfo = responseError ?? ["err" : "Unexpected media uploading error" as AnyObject] 
enter code here 
          let error = response.result.error ?? RequestManager.makeError(response.response?.statusCode ?? 500, userInfo: errorInfo) 
          completionHandler(nil, error as NSError?) 
         } 
        } 
       default: 
        completionHandler(nil, RequestManager.makeError(500, userInfo: ["err" : "Multipart encoding failed" as AnyObject])) 
       } 
     }) 
    } 

PS:我使用multipartFormData上傳B/C我需要發送一些其他的參數,以及(一旦我能夠上傳圖片)。

回答

0

我不得不添加.httpAdditionalHeaders B/C我的服務器期待某些數據:

RequestManager.sharedAlamofireManager.session.configuration.httpAdditionalHeaders = ["Accept": "application/json", "Content-Type": "multipart/form-data"] 

您可以通過將一個鍵/值對添加到此陣列來添加更多配置。

0

您應該使用

multipartFormData.append(paramData, withName: "paramName") 

字符串特性參數的情況下,你應該字符串轉換爲數據

data = string.data(using: String.Encoding.utf8)! 
multipartFormData.append(data, withName: "stringParamName") 

全碼

RequestManager.sharedAlamofireManager.upload(multipartFormData: { 
    multipartFormData in 

    //This generates an error: "The data could not be read because it isn’t in the correct format" 
    if let imageData = UIImageJPEGRepresentation(avatarImage, 1) { 
     multipartFormData.append(imageData, withName: "avatar", mimeType: "image/jpeg") 
    } 
    data = string.data(using: String.Encoding.utf8)! 
    multipartFormData.append(data, withName: "stringParamName") 

    //..... 
+0

我試過了,不幸的是不是解決方案 –