I make an application that allows user to upload image and several to our server. If I just post text data my code successfully post data to the server but when I try to post text data with image data, my server throw an exception.
here is my code:
class func Enroll(image: UIImage, date: String, studentid: String, guardianid:String, type:String){
//date,student_id,type,guardian_id,image, type
var textBody : String?
let imageData = UIImagePNGRepresentation(image)
let boundary = NSString(format: "---------------------------14737809831466499882746641449")
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
let URL: NSURL = NSURL(string: "http://api-cc.appsence.net/v1/signs")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
let body : NSMutableData = NSMutableData()
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
//fill text value here
textBody = "date=\(date)&student_id=\(studentid)&guardian_id=\(guardianid)&type=\(type)"
print("text body : \(textBody!)")
let bodyTextData = textBody!.dataUsingEncoding(NSUTF8StringEncoding);
body.appendData(bodyTextData!)
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
// if data string use data using encoding
request.HTTPBody = body
NSURLSession.sharedSession().dataTaskWithRequest(request){ (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error == nil{
print("sukses : \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")
}else{
print("ini error save \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")
}
}.resume()
}
How can I fix this issue?