this is my code that I want to upload image to server using Alamofire, it not error but it can't push image to server. what should I do?
let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let parameters = ["name": rname]
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
print(error)
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!
Alamofire.upload(multipartFormData: { MultipartFormData in
MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")
},with: urlRequest,encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject> {
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
}
}
}
} case .failure(let error):
print(error)
}
})
Try below code
let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!
let parameters = ["name": rname] //Optional for extra parameter
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
} //Optional for extra parameters
},
to:"mysite/upload.php")
{ (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)
}
}