Reputation: 813
I want to upload image as binary, as in Postman we do below
Here is my code
var url = myURLString
url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
guard let imageData = UIImageJPEGRepresentation(image, 0.4) else {
return
}
request.httpBody = imageData
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
Alamofire.request(request).responseJSON { (response) in
if let JSON = response.result.value as? NSDictionary {
print(JSON)
} else {
let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
print(message)
}
}
It seems that request is not attaching image file, returning following error message
"Response could not be serialized, input data was nil or zero length."
Upvotes: 1
Views: 7362
Reputation: 10329
Swift 4 and 5
var urlRequest = URLRequest(url: URL)
urlRequest.httpMethod = "PUT" // POST
urlRequest.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
var data = image!.jpegData(compressionQuality: CGFloat(0.5))!
URLSession.shared.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
DispatchQueue.main.async {
print(response)
guard let responseCode = (response as? HTTPURLResponse)?.statusCode, responseCode == 200 else {
if let error = error {
print(error)
}
return
}
// do your work
}
}).resume()
Upvotes: 2
Reputation: 813
For swift 3, Alamofire 4 below code will work fine
var url = myURLString
url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
guard let imageData = UIImageJPEGRepresentation(image, 0.4) else {
return
}
Alamofire.upload(imageData, to: URL(string: url)!, method: .post, headers: nil).responseJSON { (response) in
if let JSON = response.result.value as? NSDictionary {
print(JSON)
} else {
let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
print(message)
}
}
Upvotes: 6
Reputation: 105
I am retrieving image from gallery and taking the name of the image by using below code: you can use the below function.
func createMultipart(image: UIImage, callback: Bool -> Void){
// use SwiftyJSON to convert a dictionary to JSON
var parameterJSON = JSON([
"id_user": "test"
])
// JSON stringify
let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// convert image to binary
let imageData = UIImageJPEGRepresentation(image, 0.7)
// upload is part of AlamoFire
upload(
.POST,
URLString: "use your url here",
multipartFormData: { multipartFormData in
// fileData: puts it in "files"
multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "ios.jpg", mimeType: "image/jpg")
// data: puts it in "form"
multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, data, error in
let json = JSON(data!)
println("json:: \(json)")
callback(true)
}
case .Failure(let encodingError):
callback(false)
}
}
)
}
let fotoImage = UIImage(named: "foto")
createMultipart(fotoImage!, callback: { success in
if success { }
})
Upvotes: 0