Uploading an image using multi-part and Alamofire - swift

I'm trying to upload an image into my backend server. A new record gets created but no images are ever uploaded:
func uploadDish(dish:Dish, completionHandler: ((AnyObject?, ErrorType?) -> Void)){
let urlString = "http://backend.com/v1/dish"
SwiftSpinner.show("Uploading Dish...")
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
if let image = self.image {
if let imageData : NSData = UIImageJPEGRepresentation(image, 0.1){
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "testesttest.jpg", mimeType: "image/jpeg")
}
}
multipartFormData.appendBodyPart(data: "foo".dataUsingEncoding(NSUTF8StringEncoding)!, name :"name")
multipartFormData.appendBodyPart(data: "bar".dataUsingEncoding(NSUTF8StringEncoding)!, name :"address")
multipartFormData.appendBodyPart(data: "1".dataUsingEncoding(NSUTF8StringEncoding)!, name :"priceRange")
multipartFormData.appendBodyPart(data: "\(234)".dataUsingEncoding(NSUTF8StringEncoding)!, name :"lat")
multipartFormData.appendBodyPart(data: "\(234)".dataUsingEncoding(NSUTF8StringEncoding)!, name :"lng")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
print(upload.debugDescription)
break
case .Failure(let encodingError):
print(encodingError)
break
}
}
)
SwiftSpinner.hide()
}
It works in Postman:

This was actually correct, found out the bug was in the back end.
The above way is how you post images

Related

I am trying to upload file through alamofire multipart with auth token but it is not woking

here is my code but it is giving me error here
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let myURL = urls.first else {
return
}
print("import result : \(myURL)")
let headers = ["Authorization": value!]
Alamofire.upload(
.POST, "https://api-uat.softsages.com/hr/document/upload/ownerId/e2cbe0fe31a2ff48ba7890ac23e23b8e", headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"_formname")
multipartFormData.appendBodyPart(fileURL: myURL, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
here I am getting error -ype of expression is ambiguous without more context. in the code above I have added file url which i am getting from document picker and according to swagger only i have to pass file as url

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?

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

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

POST image Swift 3 using Alamofire

I'm trying to POST an image in Swift 3 using Alamofire. I'm not sure how I can send my image specified in my params. I think I need to save the photo to POST, correct? Is there a way to not have to save the photo first?
func postPhoto (image: UIImage) {
let url = try! URLRequest(url: URL(string:"http://example.com/doapost")!, method: .post, headers: nil)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(Data(), withName: "image", fileName: "file.png", mimeType: "image/png")
},
with: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if((response.result.value) != nil) {
print(response)
} else {
print("nil response")
}
}
case .failure( _):
print("Failure to post")
break
}
}
)
}