Upload Image in swift with parameter using Alamofire - swift

I want to upload an image from the gallery but it showing me some error like this
my code is like this
func groupProfile(completion:#escaping CompletionHandler){
let imageSource = pickedImage.jpegData(compressionQuality: 1.0)
let parameters = ["filename": imageSource]
let headers : HTTPHeaders = [
"token" : AuthServices.instance.authToken,
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data"
]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageSource!, withName: "filename",fileName: "Avatar.jpeg" , mimeType: "image/png")
for (key, value) in parameters
{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
let jpegData = self.pickedImage.jpegData(compressionQuality: 1.0)
multipartFormData.append(Data((jpegData)!), withName: "filename")
}, to: SAVE_IMAGE_ON_SERVER_URL,method: .put,headers: headers)
.response { response in
debugPrint(response)
}
}

I think you only need to add
multipartFormData.append(imageSource!, withName: "filename",fileName: "Avatar.jpeg" , mimeType: "image/png"), change the mimeType to "image/jpeg" and remove the following lines because it is trying to repeat the same logic.
for (key, value) in parameters
{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
let jpegData = self.pickedImage.jpegData(compressionQuality: 1.0)
multipartFormData.append(Data((jpegData)!), withName: "filename")
I have formatted to code that should upload the image as what you are trying to achieve.
func groupProfile(completion:#escaping CompletionHandler){
guard let imageData = pickedImage.jpegData(compressionQuality: 1.0) else{
return
}
let headers : HTTPHeaders = [
"token" : AuthServices.instance.authToken,
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data"
]
let upload:(MultipartFormData)->Void = { multidata in
multidata.append(imageData, withName: "filename", fileName: "Avatar.jpg", mimeType: "image/jpeg")
}
Alamofire.upload(multipartFormData: upload,
to: SAVE_IMAGE_ON_SERVER_URL,
method: .post,
headers: headers){ response in
debugPrint(response)
}
}

Related

why my swift alamofire multipart is not working?

I am doing a REST call to a webService but i am getting Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength.
What is the problem?
let params = [RESTConstants.APIParameterKey.client: UserDefaults.standard.string(forKey: ConstantsHelper.client)!, RESTConstants.APIParameterKey.token: UserDefaults.standard.string(forKey: ConstantsHelper.token)!]
AF.upload(multipartFormData: { multipartFormData in
for (key, value) in params {
multipartFormData.append((value).data(using: String.Encoding.utf8)!, withName: key)
}
if let imageData = image.jpegData(compressionQuality: 1.0) {
multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
}
}, to: "myUrl")
.responseDecodable(of: Response.self) { response in
debugPrint(response)
}

How to send UIImage Extension as parameter to server using Alamofire ppost request in Swift?

I have a postman api that requires an Extension to send with the image. Without the extension it take the image as a file. Help me to send the image with the extension or tell me the better way to do so, or let me know where i am doing wrong.Postman Image Here is my code so far:
func UPLOD(){
guard let token = UserDefaults.standard.string(forKey: "accesstoken") else {
return
}
print("Create button ACCESS KEY::::- \(token)")
let headers: HTTPHeaders = [
"x-access-token": token,
"Content-type": "multipart/form-data",
"Content-Disposition" : "form-data",
"Filename" : "Angle",
"Ext" : ".png"
]
let image = myImageView.image
let imgData = image!.jpegData(compressionQuality: 0.7)!
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData, withName: "FileToUpload", fileName: "swift_file.png", mimeType: "image/png")
print("mutlipart 1st \(multipartFormData)")
multipartFormData.append("angela".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName :"Filename")
multipartFormData.append("Image".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName :"Folder")
//multipartFormData.append("jpeg".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName :"Ext")
//multipartFormData.append(imgData, withName: "Ext", mimeType: "image/png")
}, to:"http://192.168.80.21:8800/api/v1/upload/uploadfile", method:.post, headers:headers)
{
(result) in
switch result {
case .success(let upload, _, _):
print("x:::::::::\(result)")
print("Upload;;\(upload)")
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress)")
})
upload.validate(statusCode: 200..<300)
upload.responseJSON { response in
guard response.error == nil else {
print("Pre json\(response as Any)")
let json = JSON(response)
print("JSON: \(json)")
return
}
print(response.result.value as Any)
print("Response: \(JSON(response.data as Any))")
}
case .failure(let encodingError):
print(encodingError)
}
}
}

Unable to upload multiple image to server Alamofire

I tried too many time and used many way but could not upload image to server let me know what I am doing wrong,but unable to upload image to server.
func callsendImageAPI(){
let headers: HTTPHeaders
headers = ["Content-type": "multipart/form-data",
"Accept-Language": ApiService.instance.defaults[.langugaeCode] ?? "en",
"Authorization": "Bearer " + ApiService.instance.getToken()
]
let url = BASE_URL + "uploadImages"
AF.upload(multipartFormData: { (multipartFormData) in
for item in self.carImages.enumerated() {
switch item.element {
case .photo(let photo):
let image = photo.image
multipartFormData.append(image.jpegData(compressionQuality: 1)!, withName: "images[0]", fileName: "file.jpeg", mimeType: "image/jpeg")
default:
break
}
}
},to: url, usingThreshold: UInt64.init(),
method: .post,
headers: headers).response{ response in
if((response.error != nil)){
do{
if let jsonData = response.data{
let jsonDecoder = JSONDecoder()
let JSON = try jsonDecoder.decode([RegularPostImage].self, from: jsonData)
print(JSON)
}
}catch{
print("error message")
}
}else{
print(response.error)
}
}
}
Thanks in Advance

Module 'Alamofire' has no member named 'upload'

I am trying to upload an image using swift to the server. i tried NSMutableURLRequest with URLSession. i received network connection lost. I thought it will be a better way to simply use Alamofire but got into a problem as xcode doesn't find the function update.
Any idea how to upload image with Alamofire? or find the update func?
the code for alamofire:
func uploadImageWithAlmofire(url: String) {
let params: Parameters = ["name": "abcd", "gender": "Male"]
Alamofire.upload(multipartFormData:
{
(multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.yourimageView.image!, 0.1)!, withName: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
for (key, value) in params
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:url,headers:nil)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON
{ response in
//print response.result
if response.result.value != nil
{
let dict :NSDictionary = response.result.value! as! NSDictionary
let status = dict.value(forKey: "status")as! String
if status=="1"
{
print("DATA UPLOAD SUCCESSFULLY")
}
}
}
case .failure(let encodingError):
break
}
}
}
When you check Uploading Data to a Server example, it uses AF instead of Alamofire:
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data("one".utf8), withName: "one")
multipartFormData.append(Data("two".utf8), withName: "two")
}, to: "https://httpbin.org/post")
.responseJSON { response in
debugPrint(response)
}
Try with this
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data(self.businessType.utf8), withName: "business_type")
let theFileName1 = (self.doc1.absoluteString as NSString).lastPathComponent
multipartFormData.append(self.doc1, withName: "key_value", fileName: theFileName1, mimeType: "image/png")
}, to: "https://www.test_document.php") //POST URL
.responseJSON { response in
debugPrint(response)
}

Alamofire 5 upload encodingCompletion

I'm working with Swift 4 and Alamofire 5, I upload two multibart photos and I want to print the progress
AF.upload(
multipartFormData: { MultipartFormData in
MultipartFormData.append(firstPic, withName: "first_pic", fileName: "image.jpeg", mimeType: "image/jpeg")
MultipartFormData.append(secondPic, withName: "second_pic", fileName: "image.jpeg", mimeType: "image/jpeg")
}, to: urlString, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
print(totalBytesRead)
}
upload.responseJSON { request, response, result in
print(result)
}
case .Failure(let encodingError):
print(encodingError)
}
})
and this gets an error saying
Argument labels '(multipartFormData:, to:, encodingCompletion:)' do not match any available overloads
did the library update the code or something??
Please modify according to your need
func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {
AF.upload(multipartFormData: { multiPart in
for (key, value) in params {
if let temp = value as? String {
multiPart.append(temp.data(using: .utf8)!, withName: key)
}
if let temp = value as? Int {
multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
}
if let temp = value as? NSArray {
temp.forEach({ element in
let keyObj = key + "[]"
if let string = element as? String {
multiPart.append(string.data(using: .utf8)!, withName: keyObj)
} else
if let num = element as? Int {
let value = "\(num)"
multiPart.append(value.data(using: .utf8)!, withName: keyObj)
}
})
}
}
multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")
}, with: url)
.uploadProgress(queue: .main, closure: { progress in
//Current upload progress of file
print("Upload Progress: \(progress.fractionCompleted)")
})
.responseJSON(completionHandler: { response in
//Do what ever you want to do with response
if let error = response.error {
print(error)
}
guard let data = response.value else {
return
}
print(value)
})
}
Alamofire 5 no longer requires an encodingCompletion! Instead, multipart form encoding is done as part of the standard now-asynchronous request process and will return errors on the Request, and they're available during validate and response* calls.
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: "file.jpeg", mimeType: "image/jpeg")
},
to: "http://----/new.php", method: .post , headers: headers)
.response { resp in
print(resp)
}