I am trying to upload an image to a backend client using swift. Trouble is I can't seem to get the formatting correct for the httpbody. I do not want to use a multipart form for uploading as I don't know how to handle that on the backend.
Here is the code I have.. it doesn't work when I view the image online it doesn't display and it is only like 70kb which I know is definitely not how big the image is.
var bodyString: String = "session_id=\(session_id)&location_id=\(location_id)"
bodyString = bodyString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
var body = NSMutableData.alloc()
body.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
if image != nil{
var imageData = UIImageJPEGRepresentation(image,0.5)
body = NSMutableData.alloc()
//var imageDataString = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
bodyString = "session_id=\(session_id)&location_id=\(location_id)&image_data="
bodyString = bodyString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
body.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
var imageString = "&image_data=\(imageData)"
body.appendData(imageData)
}
req.HTTPBody = body
UPDATE: so I decided to go the base64 route but it still doesn't seem to be working I think because I am encoding it as an ntf8string is this the correct way to be doing this?
var imageData = UIImageJPEGRepresentation(image,0.5)
var imageDataString = imageData.base64EncodedStringWithOptions(.allZeros)
body = NSMutableData.alloc()
bodyString = "session_id=\(session_id)&location_id=\(location_id)&tag_type=\(tag_type)&image_data=\(imageDataString)"
bodyString = bodyString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
body.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
and on the backend I am decoding it like:
image_data_decoded = base64.b64decode(image_data)