我设法使用multipart-form-data Alamofire上传文件上传文件:
Alamofire.upload(.POST, "api.myservice.com", headers: myheaders, multipartFormData: { (multipartFormData:MultipartFormData) -> Void in
multipartFormData.appendBodyPart(data: json, name: "metadata", mimeType: "application/json")
multipartFormData.appendBodyPart(data: self.data, name: "document", fileName: "photo.png", mimeType: "image/png")
}, encodingMemoryThreshold: 10 * 1024 * 1024) { (result:Manager.MultipartFormDataEncodingResult) -> Void in
}
但我看不到跟踪上传进度的方法,并且在上传完成(或失败)后调用完成块。有没有办法在Alamofire做到这一点?
注意:我知道可以上传进度,但我正在研究多部分表格数据。
答案 0 :(得分:15)
这是一种完成,失败和进度关闭的方法(感谢我的同事指出解决方案):
<div class="col-sm-12">
<div class="col-sm-12">
<div class="col-sm-6">
<div class="col-sm-12">
</div>
<div class="col-sm-12">
</div>
</div>
<div class="col-sm-6">
</div>
</div>
<div class="col-sm-12">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
</div>
</div>
</div>
答案 1 :(得分:4)
接受的答案很棒。这个也包括参数:
let image = UIImage(named: "big.jpg")!
let imageData = UIImageJPEGRepresentation(image, 1)
let coupon = textBox?.text ?? "NO coupon"
let uploadUrl = "http://example.com/upload.php"
// define parameters
let parameters : [String: String] = ["one":"some param", "two":"some other param"]
Alamofire.upload(.POST, uploadUrl, headers: nil,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData!, name: "cannotBeBlank", fileName: "image.zip", mimeType: "image/png")
// import parameters
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.data!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print("1) \(bytesWritten) 2) \(totalBytesWritten) 3) \(totalBytesExpectedToWrite)")
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
upload.responseData(self.handleResponse)
case .Failure:
self.handleError()
}
})