let URL_str = API.sendImage
let image = UIImage(named: "photo.jpg")
let imagData = UIImageJPEGRepresentation(image!, 1)!
print(imagData)
let parameters : Parameters = [
"phone" : USERDEFAULT.getPhoneNo(),
"password" : USERDEFAULT.getPassword(),
"friend_uid" : "01206921-71a5-4e14-8084-62560022c30c59e22b245278483f4c67244b-1698492849",
"conversation_id" : "3c1de3f388a5450e7c9d9c4bf6f18ec1",
]
Alamofire.upload(multipartFormData:
{ (multipartFormData) in
multipartFormData.append(imagData, withName: "file", fileName: "testImg.jpg", mimeType: "image/jpg")
for (key, value) in parameters
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to: URL_str)
{ (result) in
switch result
{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
print(response.description)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
This is my complete code, how i upload image with parameters. But issue is that Image Data before uploading: 272707 bytes &
Image Data on Server: 0 bytes. Kindly someone help me. What am i doing wrong? And Thanks in advance.
Related
I am unable to upload images to server getting. Showing upload progress upload.uploadProgress but after upload.responseJSON is nil error.
I have tried my best but couldn't solve the issue. Please anyone can help me out. What am I doing wrong? when I debug it { (result) in switch result { result is invalid.
Postman key: (parameters)
ImageList -- for images
ProjectUnitID -- 8568816
Swift Code:
if asset.type == .photo {
let displayImage = asset.fullResolutionImage!images?.append(d)
let token = UserDefaults.standard.string(forKey: "newToken")
let image = displayImage
let imgData = image.jpegData(compressionQuality: 0.2)!
let parameters = ["ProjectUnitId": 8568816]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "ImageList",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},to:"http://AddProjectUnitImages", headers: [ "Authorization":"Bearer \(String(describing: token))"]) { (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)
}
}
}
Try this if this is a server error you will get the error here,
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(profileImg, withName: "user_image", fileName: "file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
} //}, to:url!,headers:nil)
}, to:url) { (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
print(progress)
})
//To check and verify server error
upload.responseString(completionHandler: { (response) in
print(response)
print (response.result)
})
upload.responseJSON { response in
switch response.result {
case .success:
print(response)
completion(response)
case .failure(let error):
print(error)
completion(response)
}
}
case .failure(_):
print(result)
// completion(responds)
}
}
Issue was at the back end side. Rectified and now my code works perfectly fine no issues.
Thanks everyone.
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
I want to upload two images using alamofire...I tried searching it but cant find an accurate answer.Most of the people are doing by creating image array but they are using with same name. I want to do it with different image names
Try this.
func uploadImagesAndData(params:[String : AnyObject]?,image1: UIImage,image2: UIImage,image3: UIImage,image4: UIImage,headers : [String : String]?, completionHandler:#escaping CompletionHandler) -> Void {
let imageData1 = UIImageJPEGRepresentation(image1, 0.5)!
let imageData2 = UIImageJPEGRepresentation(image2, 0.5)!
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in params! {
if let data = value.data(using: String.Encoding.utf8.rawValue) {
multipartFormData.append(data, withName: key)
}
}
multipartFormData.append(imageData1, withName: "file1", fileName: "image.jpg", mimeType: "image/jpeg")
multipartFormData.append(imageData2, withName: "file2", fileName: "image.jpg", mimeType: "image/jpeg")
},
to: K_BASEURL + K_API_LOGINDATA, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload
.validate()
.responseJSON { response in
switch response.result {
case .success(let value):
print("responseObject: \(value)")
case .failure(let responseError):
print("responseError: \(responseError)")
}
}
case .failure(let encodingError):
print("encodingError: \(encodingError)")
}
})
This is how I am trying to upload an image using Alamofire. But the program crashes saying something like...'NSInvalidArgumentException', reason: '-[_SwiftTypePreservingNSNumber dataUsingEncoding:]: unrecognized selector sent to instance... I'm not able figure the exact reason.This is how I'm making the request...
for i in 1...(imageArray.count) {
for img in imageArray {
let url = "http://myapp.com/a/images_upload"
let headers = [ "Content-Type":"application/x-www-form-urlencoded"]
let imageData: Data = (UIImageJPEGRepresentation(img, 0.6) as Data?)!
print(imageData)
let parameters: [String: Any] = [
"access_token": commonVarForAccessToken,
"seller_id": idForNewOldUser,
"product_id": self.productId,
"is_default": "1",
"sequence": i,
"image": imageData ]
Alamofire.upload(multipartFormData: { (multipartFormData) in
print(parameters)
multipartFormData.append(imageData as Data, withName: "home-\(self.index)", fileName: "home-\(self.index)", mimeType: "image/jpeg")
for (key, value) in parameters {
print(key,value)
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:url)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
//Print progress
})
upload.responseJSON { response in
print(response.request) // original URL request
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
print(encodingError)
break
}}}}
Hope somebody can help...Thanks...:)
Try to use this code.It's working for me.
let para: [String: Any]
Alamofire.upload(multipartFormData: {(multipartFormData) in
for i in 0..<uploadImages.count{ multipartFormData.append(UIImageJPEGRepresentation(uploadImages[i], 0.3)!, withName: "image\(i)", fileName: "swift_file\(i).jpeg", mimeType: "image/jpg")
}
for (key, value ) in para {
multipartFormData.append((value).data(using: String.Encoding.utf8)!, withName: key)
}
}, to: apiURL)
{ (result) in
switch result {
case .success(let upload, _,_ ):
upload.uploadProgress(closure: { (progress) in
UILabel().text = "\((progress.fractionCompleted * 100)) %"
print (progress.fractionCompleted * 100)
})
upload.responseJSON { response in
guard ((response.result.value) != nil) else{
print(response.result.error!.localizedDescription)
return
}
I want to upload multipart images in my project with alamo fire some times with no reason the alamo fire file name will return nil - how can I avoid that ?
let params: Parameters = ["name": "image\(i)"]
Alamofire.upload(multipartFormData:
{
(multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(imageUploadingViewController.imageUpload[i], 1.0)!, withName: "myfile", 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: "http:example.com/api/file?api_token=\(enterViewController.api_token)&id=\(self.postID)",headers:nil)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
UploadingViewController.progressing = progress.fractionCompleted
self.UpdateState()
if progress.fractionCompleted == 1.0 {
DispatchQueue.main.async {
UploadingViewController.fine = UploadingViewController.fine + 1
}
print(UploadingViewController.fine)
self.checkUploadProgress()
print("OK Finished!")
}
})
the application will crash in this line because of fileName
multipartFormData.append(UIImageJPEGRepresentation(UploadingImagesViewController.imageUpload[i], 1.0)!, withName: "myfile", fileName: "file.jpeg", mimeType: "image/jpeg")
remember that some times it will work I don't know why this will happen!
func sendImageToServerWithURL(_ URLString: URLConvertible, method: HTTPMethod, headers: [String : String]?, parameters: [String: Any]?, imageData : Data?,imageName:String,completionHandler: #escaping CompletionHandler) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
if((imageData) != nil)
{
multipartFormData.append(imageData!, withName:imageName, fileName: "swift_file.png", mimeType: "image/png")
}
for (key, value) in parameters!
{
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:URLString ,headers : headers)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
print (response.result)
completionHandler(response)
}
case .failure( _): break
//print encodingError.description
}
}
}
i am using the method to upload pic . i check if((imageData) != nil) the data value before upload . may be this helpful.