Alamofire 4 File Upload Parameter issue - ios

Plese have a look at the pic here from postman
POSTMAN success result
but the code does not run I am missing something please help me out
var parameters = [String: String]()
parameters = [
"profile_image": "imagefile"
]
let headers: HTTPHeaders = [
"Accept": "application/json"
]
let url = "http://******/public/api/v1/profile/update-picture?api_token=" + "aySlC26ZTHtlnS0lhUpdghxkd9gKJBLXLYFUO2Jidmiisoka9iFIicwRIZFx"
let completeUrl = URL(string:url)!
let imageData = UIImageJPEGRepresentation(chosenImage!, 1)
print ("image data:: \(imageData)")
print ("chosenImage:: \(chosenImage)")
// Alamofire.upload(imageData!, to: completeUrl).response { response in
// print (response)
// }
Alamofire.upload(
multipartFormData: {
multipartFormData in
multipartFormData.append(imageData!,
withName: "imagefile",
fileName: "image.jpg",
mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
}
},
to: completeUrl,
headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON{ response in
print(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
Postman Response
Success on postman but having issue with headers, can you point out the silly mistake i have make

I believe you need to append the image this way
multipartFormData.append(imageData!,
withName: "profile_image",
fileName: "image.jpg",
mimeType: "image/jpeg")
And you don't need to set or include parameters = ["profile_image": "image file"]
As #rob mentioned, use Charles and compare the request from Postman with the request from the simulator. It will help to pinpoint what's different

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 append MultipartFormData along with other post parameters using Alamofire and session manager? [duplicate]

This question already has answers here:
Alamofire 4 upload with parameters
(2 answers)
Closed 4 years ago.
Currently I use:
func post(_ url: URL, parameters: [String: Any]?, image: UIImage?, headers: [String: String]?, success: #escaping SuccessHandler, failure: #escaping ErrorHandler) {
manager.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { [weak self] response in
//do something with a response
}
}
How can I append image to the request?
Here is my answer
Alamofire.upload(multipartFormData: { multipartFormData in
//Single image to pass here
if image != nil{
if let imageData = UIImageJPEGRepresentation(image!, 0.8) {
multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
}
}
//Here array of UIImages
if images.count != 0{
for img in images{
if let imageData = UIImageJPEGRepresentation(img, 0.8) {
multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
}
}
}
//params are your other post parameters
if let parm = params{
for (key, value) in parm {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}
}, to: "Your url here" , method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
//Success response
case .failure(let encodingError):
//Failure response
}
})
You should consider using upload method :
manager.upload(multipartFormData: { (multipartFormData) in
for (key,value) in data{
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
}
if let file = self.attachedFile{
if let f = file.getFile()
{
multipartFormData.append(f, withName: "some_name", fileName: "attachement.pdf", mimeType: "application/pdf")
}
}
}, to:"Some URL",
method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
//Success response
case .failure(let encodingError):
//Failure response
}
})

Upload files using multipart request - Swift 4

I have to upload files on server using multipart request. For network calls i am using Alamofire.
What i have done so far is below
Request Service:
Multipart request:-
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
let fileData = Filedata() // getting data from local path
let URL = try! URLRequest(url: "https://SomeUrl/upload", method: .post, headers: headers)
Alamofire.upload(multipartFormData: { (multipartFormData) in
//multipartFormData.append(fileData, withName: "image", fileName: "image", mimeType: "image/png")
multipartFormData.append(fileData, withName: "file")
}, with: URL, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
Response:-
{ Status Code: 400, Headers {
Connection = (
close
);
"Content-Type" = (
"application/json;charset=UTF-8"
);
Date = (
"Tue, 15 May 2018 10:34:15 GMT"
);
"Transfer-Encoding" = (
Identity
);
} }
[Data]: 171 bytes
[Result]: SUCCESS: {
error = "Bad Request";
message = "Required request part 'file' is not present";
path = "/files/safebolt.org/upload";
status = 400;
timestamp = "2018-05-15T10:34:15.715+0000";
}
Can anyone please tell me what i am doing wrong with request ?
Try with:
multipartFormData.append(fileData, withName: "file", fileName: "file", mimeType: "image/png")
I have created one function. Hope it works for you.
//Alamofire file upload code
func requestWith(URLString: String,
imageData: Data?,
fileName: String?,
pathExtension: String?,
parameters: [String : Any],
onView: UIView?,
vc: UIViewController,
completion:#escaping (Any?) -> Void,
failure: #escaping (Error?) -> Void) {
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
let URL = BASE_PATH + URLString
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: "fileUpload", fileName: "\(fileName!).\(pathExtension!)", mimeType: "\(fileName!)/\(pathExtension!)")
}
}, usingThreshold: UInt64.init(), to: URL, method: .post, headers: headers) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let err = response.error {
failure(err)
return
}
completion(response.result.value)
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
failure(error)
}
}
}
Try This, is an example it works for me. If you want to convert encode 64 for images add extension. If simply post the data and image this code may help.
//creating parameters for the post request
let parameters: Parameters=[
"ad_title":classText1.text!,
"ad_description":classText2.text!,
"ad_category":CategoryClass.text!,
"ad_condition":classText3.text!,
"ad_username":classText6.text!,
"ad_usermobile":classText7.text!,
"ad_city":classText8.text!,
"ad_price":classText4.text!,
"negotiable":classText5.text!,
"image1":adImage1.image!,
"image2":adImage2.image!,
"image3":adImage3.image!,
"image4":adImage4.image!
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
}, usingThreshold: UInt64.init(), to: URL, method: .post) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded = \(response)")
if let err = response.error{
print(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}

Upload an image (Base64) using Alamofire Swift 3

Iam trying to upload 2 images to server with JSON request using alamofire
and here's my code :
let parameters = ["CreditCardImage":CreditCardImage,"CreditCardBackImage":CreditCardBackImage , "CustomerID" : CustomerID]
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("MY URL", method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
// get json Response
let json = JSON(response.result.value)
print(json)
}
When i print the response iam getting message << unknown >> in the console
and i tried that in postman it's not working too what's wrong with that ? any help ?
you should use other Alamofire methods. Here is an example:
func uploadAvatar(image: UIImage) {
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
}
}, to: self.serverAddress + "/user/uploadAvatar", method: .post, headers: ["Authorization": User.shared.token], encodingCompletion: { _ in })
}
You can try this
let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!
let parameters = ["name": rname]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},
to:"mysite/upload.php")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(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)
}
})
}

Resources