用过AFNetworking
一定对上面的上传图片的方式不陌生,其中parameters
一般都放一个字典,里面放一些其他的参数
[manager POST:@"www.png.com" parameters:@{@"name":@"小沫"} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//在这里拼接formData
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
//上传成功返回responseObject
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
//失败返回error
}];
Alamofire
和AFNetworking
传的参数差不多,但是少了parameters
这个参数,如果同时要传其他的参数,需要在multipartFormData
后面拼接
let parameters = [
"par1": "value",
"par2": "value2"]
let URL = "YOUR_URL.php"
let image = UIImage(named: "image.png")
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let _image = image {
if let imageData = UIImageJPEGRepresentation(_image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
}
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseObject { (response: Response<UploadData, NSError>) -> Void in
switch response.result {
case .Success:
completionHandler?(success: true)
case .Failure(let error):
completionHandler?(success: false)
}
}
case .Failure(let encodingError):
print(encodingError)
}
})