图像上传swift上的参数缺失错误

时间:2016-01-07 05:59:14

标签: ios swift2 image-uploading multipartform-data image-upload

我正在尝试使用一些细节将图像上传到服务器,但是我一直在接收来自服务器的参数丢失错误。这是我的图片上传代码

 func uploadImages(imageData: NSData, withParams requestDict:NSDictionary, callBack:(responseDict: NSDictionary?, error: NSError?) -> ())
    {

        print(requestDict)            
        let boundary = generateBoundaryString()

        let url:NSURL = NSURL(string: String(format: "%@%@", BASE_URL, IMAGE_UPLOAD_API))!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.timeoutInterval          = FLOAT_CONSTANT_60
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

         request.HTTPBody = createBodyWithParameters(requestDict as? [String : String], filePathKey: "image", imageData: imageData, boundary: boundary)

        print(requestDict)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) in
            do {
                let JSON = try! NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments)
                guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
                    print("Not a Dictionary")
                    //get your JSONData here from dictionary.

                    return
                }
                callBack(responseDict: JSON as? NSDictionary, error: nil)
                print("JSONDictionary! \(JSONDictionary)")

            }
            catch let JSONError as NSError {
                print("\(JSONError)")
                callBack(responseDict: nil, error: JSONError)

            }

        })

     }


    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageData: NSData, boundary: String) -> NSData {
        let body = NSMutableData()

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "MyImage.jpg"

        let mimetype = "image/jpg"

        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageData)
        body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")

        return body

    }

    /// Create boundary string for multipart/form-data request
    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }

这是我的服务器api格式

"{
'deviceId' : 1234567,
'role' : 'admin',
'authToken' : 'cf01ebcd5844fde166940b06fbb267ba',
'userId' : 90490,
'appointmentId': 25067187,
'position' : 2,
'image' : ''
}"

这就是打印响应在uploadImages方法中打印的内容

{
    appointmentId = 25067187;
    authToken = b72e4d89aa53399dd3a04f1440dec704;
    deviceId = "4DF3R180-55XC-4G3C-90F8-3431537ECCAF";
    position = 2;
    role = admin;
    userId = 90490;
}

我相信image参数是filePathKey字符串并附加在请求中,但我无法打印它以在附加图像后查看请求。有没有什么我做错了,因为没有添加图像参数?

修改

这就是我调用方法的方法

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){

        dispatch_async(dispatch_get_main_queue(),{
            let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
            let imageData = UIImageJPEGRepresentation(selectedImage!, 1)

            let apiHandler = APIHandler()

            apiHandler.uploadImages(imageData!, withParams: self.createImageUploadDict(), callBack: { (responseDict, error) -> () in
                print(responseDict)


            })

        })
        self.dismissViewControllerAnimated(true, completion: nil)
    }

1 个答案:

答案 0 :(得分:0)

我想出了这个问题,代码没有任何问题,在创建请求字典时我实际上使用的是[String:AnyObject]但是在这里我使用了[String:String]这就是为什么我得到了参数缺失错误。