Alamofireでmultipart/form-dataをパラメータ付きでPostしてみた。(Swift3.0/Alamofire (4.0.1))
Just in case I forget how to use lol
Basically it is so simple, you just need to add "multipartFormData.append()".
Additional Requirement: Reorder if you would like to post many data (more than 2) because Alamofire automatically sorts post params.
Purpose
Personal Note
Development Environment
- OS X El Captain 10.11.2
- Xcode Version 8.0
Language
Swift 3.0
Alamofire 4.0.1
Source Code
Alamofire.upload(
multipartFormData: { multipartFormData in
self.addImageData(multipartFormData: multipartFormData,image: self.yourUIImage)
// If you need to post many data, you need to sort with key.
if let data = "LawQiita".data(using: String.Encoding.utf8) {
multipartFormData.append(data, withName: "yourPostData")
}
}
},
to: getUrl(),
headers: getHeader(),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print (response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
private func addImageData(multipartFormData: MultipartFormData, image: UIImage!){
var data = UIImagePNGRepresentation(image!)
if data != nil {
// PNG
multipartFormData.append(data!, withName: "targetImage",fileName: "targetImage", mimeType: "image/png")
} else {
// jpg
data = UIImageJPEGRepresentation(image!, 1.0)
multipartFormData.append((data?.base64EncodedData())!, withName: "targetImage",fileName: "targetImage", mimeType: "image/jpeg")
}
}
Alamofire.upload(
multipartFormData: { multipartFormData in
self.addImageData(multipartFormData: multipartFormData,image: self.yourUIImage)
// If you need to post many data, you need to sort with key.
if let data = "LawQiita".data(using: String.Encoding.utf8) {
multipartFormData.append(data, withName: "yourPostData")
}
}
},
to: getUrl(),
headers: getHeader(),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print (response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
private func addImageData(multipartFormData: MultipartFormData, image: UIImage!){
var data = UIImagePNGRepresentation(image!)
if data != nil {
// PNG
multipartFormData.append(data!, withName: "targetImage",fileName: "targetImage", mimeType: "image/png")
} else {
// jpg
data = UIImageJPEGRepresentation(image!, 1.0)
multipartFormData.append((data?.base64EncodedData())!, withName: "targetImage",fileName: "targetImage", mimeType: "image/jpeg")
}
}
Author And Source
この問題について(Alamofireでmultipart/form-dataをパラメータ付きでPostしてみた。(Swift3.0/Alamofire (4.0.1))), 我々は、より多くの情報をここで見つけました https://qiita.com/law/items/5efbfc353e06fefcec25著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .