Reputation: 37
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)
}
}
Upvotes: 0
Views: 337
Reputation: 21
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)
}
}
Upvotes: 1