如何使用Alamofire上传MultipartFormData
身份验证?我不明白的部分是放置.authenticate(user: username, password: password).
的位置?这就是我通常使用MultipartFormData
上传图片的方式:
Alamofire.upload(
.POST, "https://myExampleUrl/photo/upload", headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"_formname")
multipartFormData.appendBodyPart(fileURL: fileUrl, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
我认为可以在头文件中添加身份验证过程吗?
答案 0 :(得分:2)
没有太多时间来探索rilbits.com
的API。当我访问Safari中的地址时,出现以下错误:
Please add 'Authorization' or 'X-Access-Token' header to your request
这表明有两种选择:
Authorization
标题以及上传请求。以下是发送Authorization
标题(第二个选项)的方法:
let username = "username"
let password = "password"
let credentialData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": base64Credentials]
Alamofire.upload(
.POST,
"https://rilbits.com/supersafe/photo/upload",
headers: headers,
multipartFormData: { multipartFormData in
let data = "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
multipartFormData.appendBodyPart(data: data, name: "_formname")
multipartFormData.appendBodyPart(fileURL: fileURL, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
完全披露:
答案 1 :(得分:0)
Alamofire.upload
没有真正上传到这里:它只将多部分请求写入文件。
当您在.responseX
的{{1}}上致电upload
时,当实际执行请求时 。也就是说,
encodingCompletion
应该做你想做的事。
如果您使用标头进行身份验证,则设置upload.authenticate(user: username, password: password)
.responseString { ...}
的{{1}}参数仍应有效;据我所知,它应该将标题转发到headers
。您可以通过将Alamofire.upload
转储到控制台来验证这一点,也可以像正常请求一样将标头设置为upload
。