将图像上载到RESTful API

时间:2016-01-26 20:23:06

标签: ios json swift

你好我成功将数据发布到服务器但这次我想将图像上传到服务器。我正在使用此功能发布没有图像的数据

static func postToServer(url:String,params:Dictionary<String,NSObject>,image:String?, completionHandler: (NSDictionary?, String?) -> Void ) -> NSURLSessionTask {


        let request = NSMutableURLRequest(URL: NSURL(string: url)!)


        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"
    if(params["data"] != "get"){
        do {

            let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)

            let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
            print("dataString is  \(dataString)")

            request.HTTPBody = data//try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)


        } catch {
            //handle error. Probably return or mark function as throws
            print("error is \(error)")
            //return
        }

    }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
            // handle error
            guard error == nil else { return }

            //print("Response: \(response)")
            let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
             completionHandler(nil,"Body: \(strData!)")
           //print("Body: \(strData!)")

            let json: NSDictionary?
            do {
                json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            } catch let dataError {
                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                print(dataError)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
              print("Error could not parse JSON: '\(jsonStr)'")
                completionHandler(nil,"Body: \(jsonStr!)")

                // return or throw?
                return
            }


            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it

                completionHandler(parseJSON,nil)
                //let success = parseJSON["success"] as? Int
                //print("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                completionHandler(nil,"Body: \(jsonStr!)")
            }

        }

        task.resume()
        return task
    }

现在我必须发送图像,我想我必须这样做

var imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)

var params = ["image":[ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]]

现在的问题是如何在上面的params变量中添加这些参数。我的意思是现在我的参数格式就像这样

{
  "email" : "hello",
  "password" : "hello"
}

1 个答案:

答案 0 :(得分:0)

你能不能将它们添加到你已经拥有的参数中,就像这样?

var params = ["email":"hello", "password":"hello"]

params["image"] = ["content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]