Image Upload not working, iOS Swift Multipart - swift

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

Related

Alamofire 5.4 upload progress issue

I am working on an app where I need to upload images and everything was working until I updated Alamofire to version 5.4.2 where I had a problem with upload progress.
The progress is showing 2 values.
func uploadImage(url: String, image: UIImage, params: [String: String], header: HTTPHeaders) {
AF.upload(multipartFormData: { (mp) in
if let imgData = image.jpegData(compressionQuality: 1.0) {
mp.append(imgData, withName: "image[0]", fileName: "\(UUID().uuidString).jpg", mimeType: "image/jpeg")
}
for (key, value) in params {
mp.append(value.data(using: .utf8)!, withName: key)
}
}, to: url, method: .post, headers: header)
.uploadProgress { (progress) in
let frac = progress.fractionCompleted
let percent = Int(frac * 100)
SVProgressHUD.showProgress(Float(frac), status: "\(percent)%")
print("\(percent)%")
}
.responseJSON { (response) in
SVProgressHUD.dismiss()
switch response.result {
case .success:
print("success !!")
case .failure(let error):
print(error.localizedDescription)
}
}
}
12%
100%
Is there any ideas how to fix this?

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

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

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

upload array of images with alamofire multipart

i upload array of images to server with alamofire multipart it uploades only first image (number of times array count) and doesnot upload the rest of images, i check every thing when get images from image picker to before and after appending image to multipart
extension profileViewController{
#objc private func UploadImage()
{
let headers = ["Authorization": "Bearer \(AuthService.instance.Auth_Token)"]
Alamofire.upload(multipartFormData: { multipartFormData in
if self.ImageArray?.isEmpty == false{
for (index, image) in self.ImageArray!.enumerated(){
print(index)
var imageData = image.jpegData(compressionQuality: 0.6)
print(imageData)
multipartFormData.append(imageData!, withName: "photos[]", fileName: "\(self.RandomString(length: 10)).jpeg",mimeType: "image/jpeg")
print(imageData)
imageData?.removeAll()
}
}else{
return
}
}, usingThreshold:UInt64.init(),
to: "http://couponsub.farid.azq1.com/api/save-user-photos"/*upload_imageUrl*/, //URL Here
method: .post,
headers: headers, //pass header dictionary here
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
print("the status code is :")
upload.uploadProgress(closure: { (progress) in
print(progress.fractionCompleted)
//self.ProgressBar.progress = CGFloat(Float(progress.fractionCompleted))
})
upload.responseJSON { response in
if response.result.isSuccess == true{
KRProgressHUD.dismiss()
}
print("the resopnse code is : \(String(describing: response.response?.statusCode))")
let json = try! JSON(data: response.data!)
print(json)
}
break
case .failure(let encodingError):
print("the error is : \(encodingError.localizedDescription)")
break
}
})
}
}
func uploadMultipleImages(imagesData:[Data]){
Alamofire.upload(multipartFormData: { multipartFormData in
// import image to request
for imageData in imagesData {
multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: urlString,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
}
case .failure(let error):
print(error)
}
})
}