2016-09-22 101 views
11

我們如何在Alamofire 4.0的上傳功能中添加認證標頭?Alamofire 4.0上傳MultipartFormData標頭

下面是示例代碼,但我認爲沒有辦法在函數中添加標題。

Alamofire.upload(
    multipartFormData: { multipartFormData in 
     multipartFormData.append(unicornImageURL, withName: "unicorn") 
     multipartFormData.append(rainbowImageURL, withName: "rainbow") 
    }, 
    to: "https://httpbin.org/post", 
    encodingCompletion: { encodingResult in 
     switch encodingResult { 
     case .success(let upload, _, _): 
      upload.responseJSON { response in 
       debugPrint(response) 
      } 
     case .failure(let encodingError): 
      print(encodingError) 
     } 
    } 
) 

上一頁alamofire的版本支持直接添加標題,但不是新的。有任何想法嗎?

回答

42

我得到了解決方案。

Alamofire.upload(multipartFormData:{ multipartFormData in 
     multipartFormData.append(unicornImageURL, withName: "unicorn") 
     multipartFormData.append(rainbowImageURL, withName: "rainbow")}, 
     usingThreshold:UInt64.init(), 
     to:"https://httpbin.org/post", 
     method:.post, 
     headers:["Authorization": "auth_token"], 
     encodingCompletion: { encodingResult in 
     switch encodingResult { 
     case .success(let upload, _, _): 
      upload.responseJSON { response in 
       debugPrint(response) 
      } 
     case .failure(let encodingError): 
      print(encodingError) 
     } 
    }) 

希望它能幫助你。

+0

感謝您的接受。我有一個相關的圖片上傳與其進展相關的問題。如果你知道那麼你能幫我嗎?我現在增加了關於SO的問題。 –

+0

http://stackoverflow.com/questions/39631823/swift-3-alamofilre-4-0-multipart-upload-with-progress。 –

+0

Alamofire 4中的音頻文件如何? - 我嘗試以這種形式發送音頻文件:multipartFormData.append(audioLocalPath,withName:「file」,fileName:「file」,mimeType:「application/octet-stream」),但發生此錯誤:multipartEncodingFailed(Alamofire.AFError .MultipartEncodingFailureReason.bodyPartFileNotReachableWithError(file:/// var/mobile/Containers/....... /Documents/item.mp3,NSUnderlyingError = 0x16049100 {Error Domain = NSPOSIXErrorDomain Code = 2「No such file or directory」}} )) - 哪裏有問題?請求或壞音頻路徑? – Saeid

相關問題