Skip to content

Instantly share code, notes, and snippets.

@DejanEnspyra
Created July 2, 2017 07:55
Show Gist options
  • Save DejanEnspyra/5bae2a301b2b2bb5de3109344345617f to your computer and use it in GitHub Desktop.
Save DejanEnspyra/5bae2a301b2b2bb5de3109344345617f to your computer and use it in GitHub Desktop.
Alamofire 4 — Multipart file upload with Swift 3 (http://theappspace.com/multipart-file-upload/)
func requestWith(endUrl: String, imageData: Data?, parameters: [String : Any], onCompletion: ((JSON?) -> Void)? = nil, onError: ((Error?) -> Void)? = nil){
let url = "http://google.com" /* your API url */
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData{
multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error{
onError?(err)
return
}
onCompletion?(nil)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}
}
@KarinaFernandez
Copy link

Thank you so much! You save my day!

@asar1
Copy link

asar1 commented Sep 13, 2018

Thanks man,
Really appreciate your help!

@amralkhayat
Copy link

thank you very much

@MikhailovAl
Copy link

Thanks dude!

@abbas-mulani
Copy link

Thank you so much.

@akhiljohny
Copy link

Thanku 👍 Saved my time.
withName: "image" //change parameter name here.

@SethuSenthil
Copy link

Hey, what dependencies do I need to add? I'm new to swift and iOS app development.

@Mayankpalotra
Copy link

Mayankpalotra commented Jun 14, 2019

Thanks man u save my lot's of efforts.

@thenooralam
Copy link

how can I get the request if I want to cancel that upload request?

@MallikarjunH
Copy link

Fantastic. Its working fine for me

@Mohamed-AbdulRaouf
Copy link

Thank you

@vinothvino42
Copy link

Thanks. I'm having response like this

Response status code was unacceptable: 400.

My backend team saying that we're not getting any data from your side. But I'm sending the image as data only. Anyone have idea ?

@29satnam
Copy link

Still saving lives!

@digvijay1331
Copy link

when the app is entered to background API failed, how to handle?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment