update post request alamofire - ios

I am uploading an image with parameters (Full name, username, email) to my server with the following code, using Alamofire:
func uploadImageData(imageView: UIImageView, fullNameToPass: String, userNameToPass: String, emailToPass: String){
//parameters
let parameters = [
"full_name" : fullNameToPass,
"user_name" : userNameToPass,
"email" : emailToPass
]
let URL = "https://webiste/add_user.php"
profileData.fetchFromDatabase()
let filename = "\(profileData.getEmail()).jpg"
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(imageView.image!, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: filename, mimeType: "image/jpg")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
print("success")
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("Failure:\(encodingError)")
}
})
}
This part works and it all gets saved.
Now I want the user to be able to edit and update the profile. I am using the following but it does not work, can you tell me why?:
func updateImageData(imageView: UIImageView, fullNameToPass: String, userNameToPass: String, emailToPass: String, userID: String){
//parameters
let parameters = [
"full_name" : fullNameToPass,
"user_name" : userNameToPass,
"email" : emailToPass,
"userID" : userID
]
let URL = "https://webiste/edit_user.php"
profileData.fetchFromDatabase()
let filename = "\(profileData.getEmail()).jpg"
print("all\(fullNameToPass), \(userNameToPass), \(emailToPass), \(userID), filename: \(filename)")
Alamofire.upload(.POST, URL, multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(imageView.image!, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: filename, mimeType: "image/jpg")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
print("success")
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("Failure:\(encodingError)")
}
})
}

Related

I want to upload image to multipart form data using alamofire swift 5

I want to upload png image to URL like postman , i used postman
postman screenshot
I used this function to upload png image to url using post method using Alamofire
this is upload function , but it return error code 500 Internal server error although it success with code 200 in postman
static func updateProfileImage(image : UIImage , result : #escaping()->()) {
if let user = UserDefaults.standard.string(forKey: "mail") , let imgData = image.pngData(){
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append("form-data".data(using: .utf8 ,allowLossyConversion: false)!, withName: "Content-Disposition")
//multipartFormData.append("name".data(using: .utf8 ,allowLossyConversion: false)!, withName: "fileUpload")
multipartFormData.append(imgData, withName: "fileUpload", mimeType: "image/png")
},
to: URLs.profileImage+user,method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
print(response)
}
case .failure( _):
print("error")
}
}
)
}
I have code of multipart data request follows, I hope this will help you.
Alamofire.upload( multipartFormData: { multipartFormData in
// parameters is method arguments in my webs ervice call method
for (key, value) in parameters {
if let data = (value as! String).data(using: .utf8) {
multipartFormData.append(data, withName: key)
}
}
let imageData = image?.jpegData(compressionQuality: 0.5)
multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "image/jpeg")
// getURL(.addProfile) will create url, method from my structure
// getHeaders() will return required header from that method
}, to: getURL(.addProfile), headers: getHeaders(), encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response(completionHandler: { (defaultDataResponse) in
guard let httpResponse = defaultDataResponse.response else {
completion(nil, defaultDataResponse.error)
return
}
if httpResponse.statusCode == 200 {
// Success Code
} else {
// Failed code
}
})
case .failure(let encodingError):
// Failed code.
}
})
Try this
func generateBoundary() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
//Set Headers with required auth
let boundary = generateBoundary()
let headers = ["content-type": "multipart/form-data; boundary=\(boundary)",
"Content-Type": "application/json",
"cache-control": "no-cache"]
//Api Call
Alamofire.upload(multipartFormData:{ multipartFormData in
if let image = imageData {
multipartFormData.append(image, withName: "<param_key>", fileName: objIdentityDetails.fileName ?? (String(Date().timeIntervalSince1970) + ".jpeg"), mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append(value?.data(using: String.Encoding.utf8) ?? Data(), withName: key)
}},
usingThreshold:UInt64.init(),
to: try! <URL>,
method: .post,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseObject { (response: <model>) in
switch response.result {
case .failure (let error):
//Error
case .success (let responseObject):
//response
}
}
case .failure(let encodingError):
//Error
}
})
You can use this following code to upload :
Alamofire.upload(multipartFormData:{ multipartFormData in multipartFormData.append(img, withName: "image", fileName: "image.png", mimeType: "image/png") },
"img" - Is Your Image Data &
"withName" - Is Your Name In Postman &
"fileName" - Your Image Name Which You Want To Upload

How to upload image using Alamofire with token&parameters?

I use Alamofire to upload images, however the upload is unsuccessful. I also bring token & parameters to server.
I don't know whether I add token & parameters correctly or not.
What's wrong with me to using Alamofire?
Have any suggestion?
Thanks.
func uploadWithAlamofire(image:UIImage, imageData:Data, imageUrl:URL) {
let parameters = ["avatar":imageData]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: user.id, fileName: "\(user.id).jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value, withName: key)
}
}, to: apiUrl , method: .put, headers: ["Authorization": "Bearer \(token)"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
photoImage = info[UIImagePickerControllerOriginalImage] as! UIImage
photoImageView.image = photoImage
let imageName:String = user.id + ".jpg"
let documentsPath = NSHomeDirectory().appending("/Documents/Icon/")
let imagePath = documentsPath.appending(imageName)
let imageUrl = URL(fileURLWithPath: imagePath)
print("imageUrl is here:\(imageUrl)")
let imageData:Data = UIImageJPEGRepresentation(photoImage, 0.001)!
do {
try imageData.write(to: imageUrl,options: .atomic)
} catch let error {
print(error)
}
uploadWithAlamofire(image: photoImage, imageData: imageData, imageUrl: imageUrl)
self.dismiss(animated: true, completion: nil)
}
Try this:
func uploadImageWith(param params:Dictionary<String,String>,image:UIImage?,handler:#escaping ((Dictionary<String,Any>?,Int) -> Void)) {
// let keyJson = "json".dataUsingEncoding(NSUTF8StringEncoding)!
print("Params:\(params)")
let BASE_URL = "http://"
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
}
if image != nil{
let imgData = UIImageJPEGRepresentation(image!, 0.5)
if imgData != nil {
multipartFormData.append(imgData!, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")
}
}
},
to: BASE_URL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print_debug("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict,(response.response!.statusCode))
}
else{
handler(nil,(response.response!.statusCode))
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil,(response.response!.statusCode))
break
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
USE
uploadImageWith(param: ["key":"value"], image: UIImage(name:"icon")) { (response, statusCode) in
print(response)
}
You have to pass the params and image object and you get the response as a Dictionary object in closure.
Use this function to upload image to the server with token and parameters
func uploadImageAndData(){
var parameters = [String:AnyObject]()
parameters = ["token": token,
"Name": Name]
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)
}
})}
Works for the Alamofire 3.0+

Getting image URL after uploading to Imgur API using Swift 3

I am uploading images anonymously using the Imgur API and Alamofire. However, I am not getting the url in the response json. Here is my code:
static func post(image: UIImage, for username: String) {
let imageData = UIImagePNGRepresentation(image)
let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
let url = "https://api.imgur.com/3/upload"
let parameters = [
"image": base64Image
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: username, fileName: "\(username).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: url, method: .post, headers: ["Authorization": "Client-ID " + Constants.IMGUR_CLIENT_ID],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
print(response) // url nowhere to be found
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
Here is the printed response:
The issue in your code is that you are just printing the response of the request, you actually need to parse that into JSON and than check the response of your request, it does contain the image url you just uploaded.
This is how you should parse the response and get the image url.
static func post(image: UIImage, for username: String) {
let imageData = UIImagePNGRepresentation(image)
let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
let url = "https://api.imgur.com/3/upload"
let parameters = [
"image": base64Image
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: username, fileName: "\(username).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: url, method: .post, headers: ["Authorization": "Client-ID " + Constants.IMGUR_CLIENT_ID],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
//This is what you have been missing
let json = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as! [String:Any]
print(json)
let imageDic = json?["data"] as? [String:Any]
print(imageDic?["link"])
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}

Image uploading with parameters using Alamofire in Swift

I am using Alamofire for my data post to the server. I ahve an image which I want to upload to server in Data form with some other parameters. In Alamofire, I am using multipartFormData method to post all the parameters and image. Server needs data to be in JSON format with parameters which is shown below:
{"product_name": "almondsfdsfsdf",
"product_price": "400",
"product_img": image.jpg}
I am trying but it gives me a failure in response. Here is my code of what I am doing in swift with alamofire:
let productName = itemNameTF.text!
let productPrice = itemPriceTF.text!
let productImage:UIImage = itemImage.image!
let url = "URL"
let parameter = ["product_name": productName, "product_price": productPrice]
let headers : HTTPHeaders = ["Content-Type": "application/json","Authorization" : "Token abcd"]
Alamofire.upload(multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(productImage, 0.5){
multipartFormData.append(imageData, withName: "image", fileName: "file.png", mimeType: "image/png")
}
for (key,value) in parameter {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: url,method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload,_,_):
upload.responseJSON { response in
print(response.request)
print(response.response)
print(response.result)
print(response.data)
}
break
case .failure(let encodingError):
print("error: \(encodingError)")
break
}
})
My server accept image in BLOB data. If anyone could help me. Thank you!
Try to change this line:
multipartFormData.append(imageData, withName: "image", fileName: "file.png", mimeType: "image/png")
To this:
multipartFormData.append(imageData, withName: "product_img", fileName: "image.jpg", mimeType: "image/jpeg")
Please take reference from below method to get the answer(Works for the Alamofire 3.0+).
func uploadImageAndData(){
var parameters = [String:AnyObject]()
parameters = ["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)
}
})
}

Multipart-form (image,parameters,headers) Post request with Alamofire in swift

Firstly, i want to say i am new to swift, and know a little.So any help would be appriciated. I have a multipart-data form which has a image (profile-image), a few parameters (first-name, last-name) and headers(userid, hashCode). I want to send a POST request to submit the form.
I have been able to make POST request with only, headers and other parameters except image as:
let headers = [
"user_id": (Helper.getUserInfo()?.user_id)!,
"hash_code":(Helper.getUserInfo()?.hash_code)!,
]
let params = [
"name": self.name.text!,
"address":self.address.text!]
Alamofire.request(.POST, kFormUrl, parameters:params ,headers:headers).responseJSON { [weak self] response in
//working fine
}
But how to send image as a file (not base-64string) i.e. direct file upload with parameters and headers.
Thanks in advance
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)
}
})
}
let userImageURL = NSURL(string: "your image url" as String)
let data = NSData.init(contentsOfURL: userImageURL!)
Alamofire.upload(
.POST,registerUrl!,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data:"N".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"flag")
multipartFormData.appendBodyPart(data: data!, name: "image", fileName: "pic.jpg", mimeType: "image/png")
multipartFormData.appendBodyPart(data: facebookId.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"facebook_id")
multipartFormData.appendBodyPart(data: nameString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"first_name")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response)
let dict = response.result.value as! NSDictionary
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
I use Alamofire (Swift 2.3) to send multipart with progress.
func upload(URLRequest: Router, onProgress: (progress: Float?) -> Void, completion: (json: AnyObject?, error: Error?) -> Void) {
let headers:[String: String] = [:]
let router = URLRequest.URLRequest
let tuple = URLRequest.parameters
let parameters = tuple.0!
let imagesData = tuple.1
let url = router.URLString
self.manager!.upload(
.POST,
url,
headers: headers,
multipartFormData: { (multipartFormData: MultipartFormData) -> Void in
for value in imagesData {
var mimeType = "video/jpg"
var bodyName = "images"
let filename = value.uniqueName
if value.mediaType == ReporterMediaType.image {
mimeType = "image/jpg"
bodyName = "images"
} else if value.mediaType == ReporterMediaType.video {
mimeType = "video/quicktime"
bodyName = "video"
} else if value.mediaType == ReporterMediaType.videoFrame {
mimeType = "image/jpg"
bodyName = "videoFrame"
}
multipartFormData.appendBodyPart(
data: value.data,
name: bodyName,
fileName: filename,
mimeType: mimeType)
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
},
encodingCompletion: { (encodingResult) -> Void in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
if response.result.isSuccess || response.response?.statusCode == 200 {
completion(json: upload, error: nil)
} else {
dispatch_async(dispatch_get_main_queue()) {
completion(json: nil, error: response.result.error)
}
}
}
upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
onProgress(progress: progress)
}
case .Failure:
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
break
}
}) }
func multipartImage(data:Data?, url:String,jsonInput:[String: String],controller:UIViewController, completion: #escaping (_ result: DataResponse<Any>) -> Void) {
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["Headerkey"] = "Headerkey"
Alamofire.upload(multipartFormData:
{ (multipartFormData) in
if data != nil {
multipartFormData.append(data!, withName:"user_image", fileName:"image.jpg", mimeType:"image/jpeg")
}else{
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: "user_image")
}
for (key, value) in jsonInput
{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:url, method: .post, headers: headers)
{ (result) in
switch result {
case .success(let upload, _ , _ ):
upload.uploadProgress(closure:
{ (progress) in
print(String(format:"%.0f%#",Float(progress.fractionCompleted)*100,"%")))
})
upload.responseJSON { response in
if showLoader == true
{
MBProgressHUD.hide(for: controller.view, animated: true)
}
completion(response)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
}

Resources