Unable to upload multiple image to server Alamofire - swift

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

Related

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)
}
}
}

Upload Image in swift with parameter using Alamofire

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)
}
}

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)
}

Upload images to the server using Alamofire

The following problem arose, the fact is that sometimes images are not uploaded to the server. All the data is correct, the image is present, the variables are arranged in the correct order, the function reports a successful upload, but sometimes the images still do not reach the server. There are no such problems with the Retorfit library, but with Alamofire it often arises. I can not figure out yet why.
class func write_photo(params:[String:String],image:UIImage, in_position:String, completion:_ js:String, _ success:Bool -> Void, failure:_ errorMessage:String,_ failure:Bool -> Void) {
let url = BaseURL + "xdb_items.write_photo"
let URL = try! URLRequest(url: url, method: .post)
let in_idclient = params["in_idclient"]
let in_iditem = params["in_iditem"]
let imgData = UIImageJPEGRepresentation(image, 0.5)!
sessionManagerImage.upload(multipartFormData: { multipartFormData in
multipartFormData.append((in_idclient?.data(using: String.Encoding.utf8)!)!, withName: "in_idclient")
multipartFormData.append((in_iditem?.data(using: String.Encoding.utf8)!)!, withName: "in_iditem")
multipartFormData.append(imgData, withName: "in_filename", fileName: "photo", mimeType: "image/png")
multipartFormData.append((in_position.data(using: String.Encoding.utf8)!), withName: "in_position")
}, with: URL, encodingCompletion: {
encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { response in
completion("", true)
}
case .failure(let encodingError):
print("ERROR RESPONSE: \(encodingError)")
}
})
}
my friends, when I did the application rollout, the Xcode issued such a warning on the id_item variable: could not execute support code to read Objective-C class data in the process. at real iPhone device maybe this is the problem
found an error, status code 500, because of what it can occur?
Postman work great! Screenshot Postman:
enter image description here
enter image description here
Code that Postman offers, but I need Alamofire:
import Foundation
let headers = [
"content-type": "multipart/form-data; boundary=----WeXXXXXXXXXXXXXXXXXXrZu0gW",
"Authorization": "Basic dXXXXXXXXXXXX=",
"cache-control": "no-cache",
"Postman-Token": "2c1bXXXXXXXXXXXXXXXXX4e"
]
let parameters = [
[
"name": "in_filename",
"fileName": "/home/iv/Рабочий стол/Скрины/Скрин6.png"
],
[
"name": "in_idclient",
"value": "516"
],
[
"name": "in_iditem",
"value": "1232"
],
[
"name": "in_position",
"value": "5"
]
]
let boundary = "----WeXXXXXXXXXXXXXXXXXXrZu0gW"
var body = ""
var error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
if (error != nil) {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string: "http://XXXXXXXXXX:XXXX/XX/xdb_items.write_photo")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
try instead of this
multipartFormData.append(imgData, withName: "in_filename", fileName: "photo", mimeType: "image/png")
to
multipartFormData.append(imgData, withName: "profile_photo")
may be this will helpful for you
let imageData : Data! = (UIImage converted to Data)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg")
}, to: NSURL(string: "http://URL you want to upload it to")! as URL)
{ (result) in
switch result {
case .success(let upload, _, _):
//Success
case .failure(let encodingError):
//Failure
}
}

Image Upload not working, iOS Swift Multipart

I have to upload an image to the server, but i am getting unusual behaviour,
if let imgdata = UIImageJPEGRepresentation(#imageLiteral(resourceName: "vishal"), 0.2) {
let headers: HTTPHeaders = [
"token": authToken,
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgdata, withName: "image", fileName: "image.png", mimeType: "image/png")
}, usingThreshold: UInt64.init(), to: url, method: .patch, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let _ = response.error{
return
}
if let value = response.result.value {
let json = JSON(value)
print(json)
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
in a new project, this code works fine and uploads the image to the server, but in my old project for the same code, api call is successful but image is not uploaded
Please help