cURL with Alamofire - Swift - multipart/form-data
Alamofire has an example in their documentation using Alamofire.upload(_:URLString:headers:multipartFormData:encodingMemoryThreshold:encodingCompletion:)
that looks like it will answer your question (note that in their example, the headers
and encodingMemoryThreshold
parameters have a default value if you don't supply one).
Also see their documentation on the various appendBodyPart()
methods on a MultipartFormData class instance.
So, a way in which your provided example code could be modified might be:
func getOCR(image: UIImage) {
let url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1"
let apiKey = "xxx-xxx-xxx-xxx-xxx"
let mode = "document_photo"
let imageData = UIImagePNGRepresentation(image)
Alamofire.upload(
.POST,
URLString: url,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(
data: apiKey.dataUsingEncoding(NSUTF8StringEncoding)!,
name: "apikey"
)
multipartFormData.appendBodyPart(
data: mode.dataUsingEncoding(NSUTF8StringEncoding)!,
name: "mode"
)
multipartFormData.appendBodyPart(
data: imageData!,
name: "file",
fileName: "testIMG.png",
mimeType: "image/png"
)
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { _, _, JSON in println(JSON) }
case .Failure(let encodingError):
println(encodingError)
}
}
)
}
Multipart form data upload with Alamofire shows file missing in server
try by adding file name for your image
like this
and withName key will contain Key name to your image on server
let profileKey = "profileImage"
multiPartData.append(imgData, withName: profileKey, fileName: filename, mimeType: "image/jpg")
Swift Alamofire multipart form data URLRequest has no member failure
The Alamofire 5.0 migration document says this:
MultipartFormData
’s API has changed and the top level upload methods to create and upload MultipartFormData have been updated to match other request APIs, so it’s not longer necessary to deal with the Result of the multipart encoding.
(https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md)
The code that you're using looks to be from an earlier version. In 5.0, the trailing closure uses a URLRequest
as its parameter (explaining the errors that you're seeing).
The Usage guide (https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) provides this as an example of uploading multipart form data:
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data("one".utf8), withName: "one")
multipartFormData.append(Data("two".utf8), withName: "two")
}, to: "https://httpbin.org/post")
.responseDecodable(of: HTTPBinResponse.self) { response in
debugPrint(response)
}
(HTTPBinResponse
is an example of a Decodable
that you can replace with your own).
Besides responseDecodable
, it looks like you can also use responseJSON
, responseData
, responseString
etc.
Note that all of these are appended with a .
after the closing )
of the call -- not as a trailing closure.
Multipart-form (image,parameters,headers) Post request with Alamofire in swift
you can use Alamofire 3.0+ below code
func uploadImageAndData(){
//parameters
let gender = "M"
let firstName = "firstName"
let lastName = "lastName"
let dob = "11-Jan-2000"
let aboutme = "aboutme"
let token = "token"
var parameters = [String:AnyObject]()
parameters = ["gender":gender,"firstName":firstName,"dob":dob,"aboutme":aboutme,"token":token,"lastName":lastName]
let URL = "http://yourserviceurl/"
let image = UIImage(named: "image.png")
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: "image", 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, _, _):
print("s")
upload.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
How to send data along with an image using Alamofire multipartFormData in swift 5
Got it fixed! Below is the code.
func Post(imageOrVideo : UIImage?){
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-Type": "multipart/form-data"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "landing.jpeg", mimeType: "image/jpeg")
multipartFormData.append(self.Pharmacy_name.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "name")
multipartFormData.append(self.Address_line1.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "address_line_1")
multipartFormData.append(self.Address_line2.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "address_line_2")
multipartFormData.append(self.Start_time.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "open_at")
multipartFormData.append(self.close_time.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "close_at")
multipartFormData.append(self.contact_number.text!.data(using: .utf8, allowLossyConversion: false)!, withName: "phone_no")
multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "longitude")
multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "latitude")
multipartFormData.append("1".data(using: .utf8, allowLossyConversion: false)!, withName: "id")
multipartFormData.append(self.token.data(using: .utf8, allowLossyConversion: false)!, withName: "api_token")
},
to: "url", method: .post , headers: headers)
.response { resp in
print("response is:" , resp)
}
Hope this helps someone.
ios swift 4 - Alamofire post parameter with UIimage file (convert curl to alamofire)
let data = UIImagePNGRepresentation(image)!
let headers = ["Authorization": "...",
"X-Storage-Id": "..."]
let parameters = ["fileItems[0].replacing": "true",
"fileItems[0].path": "/path/something"]
Alamofire.upload(multipartFormData: { form in
form.append(data,
withName: "fileItems[0]",
fileName: "file1.png",
mimeType: "image/png")
parameters.forEach({
form.append($0.value.data(using: .utf8)!, withName: $0.key)
})
}, to: "https://example.com/uploadfiles", method: .post, headers: headers) { result in
//switch result { ... }
}
Using FORM DATA with Alamofire
So my solution is.... you have to specify the Parameter Encoding in Alamofire. So the code will look like this.
Swift 2.0
func registerNewUserFormData(completionHandler: (Bool, String?) -> ()){
// build parameters
let parameters = ["email": "test@test.cz", "password": "123456"]
// build request
Alamofire.request(.POST, urlDomain + "register", parameters: parameters, encoding: .URL).responseJSON { response in
switch response.result {
case .Success:
print("Validation Successful")
if let JSON = response.result.value {
print(JSON)
}
case .Failure(let error):
print(error)
}
}
}
Related Topics
Why It Is Called the Memberwise Initialiser
How to Use a Value Type Object as a Reference Type
How to Create Public Extensions, in a Shared Framework, for Xctest
Swiftui 2 Pop to Root View with No Scene Delegate
Apple Vision - Barcode Detection Doesn't Work for Barcodes with Different Colours
Scntext Alignment Not Working in iOS
Swift: Visual Glitches When Presenting a Main and Alternative (Login/Onboarding) Flow
How to Create Project Without Story Board in Xcode 6 (Swift)
Get Color of Point in a Skscene Swift
How to Check If Airpods Are Connected to Iphone
How to Immediately See Swift Errors in Appcode
Create a Swift Dictionary Subclass
How to Integrate Uisearchcontroller with Swiftui
Swift Create Byte Buffer Holder for Nsstream
How to Convert Data of Int16 Audio Samples to Array of Float Audio Samples