将图像转换为Base64代码(状态代码为500)

时间:2018-03-19 05:21:33

标签: ios swift api base64

当我想在服务器上发送一些数据时,我遇到了一些错误。而这个问题是当我将图像转换为Base64代码时,它会产生一些问题。请帮我解决这个问题。数据格式不正确,状态代码为500.我不知道如何解决这个问题。

错误:

admin:upload_csv

我的代码是:

<NSHTTPURLResponse: 0x1c043c2c0> { URL: http://192.168.1.58/api/visitor/store } { Status Code: 500, Headers {

    "Cache-Control" =     (

        "no-cache, private"
    );
    Connection =     (
        close
    );

    "Content-Type" =     (

        "text/html; charset=UTF-8"

    );

    Date =     (
        "Mon, 19 Mar 2018 05:11:06 GMT"
    );
    Server =     (

        "Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1"

    );

    "Transfer-Encoding" =     (

        Identity

    );

    Vary =     (

        Authorization

    );

    "X-Powered-By" =     (
        "PHP/7.1.1"
    );

    "X-RateLimit-Limit" =     (

        60

    );
    "X-RateLimit-Remaining" =     (
        59
    );
} }

The data couldn’t be read because it isn’t in the correct format.

2 个答案:

答案 0 :(得分:1)

我正在给你一个完整的解决方案并尝试一下。

步骤1:声明全局变量。

var imageDataForApi:Data!

第2步:将此代码放在imagePickerController didFinishPickingMediaWithInfo

 if let image = info[UIImagePickerControllerEditedImage] as? UIImage
    {
        imageview.image = image
        let sonu = getFileName(info: info)
        print(sonu)
        if sonu == "JPG"
        {
            imageDataForApi = UIImagePNGRepresentation(image)
        }
        else if sonu == "PNG"
        {
            imageDataForApi = UIImageJPEGRepresentation(image, 0)
        }
    }
    self.dismiss(animated: true) { () -> Void in

    }

步骤3:粘贴此函数blow viewdidload。

func getFileName(info: [String : Any]) -> String {

    if let assetPath = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [assetPath], options: nil)
        let asset = result.firstObject
        let fileName = asset?.value(forKey: "filename")
        let fileUrl = URL(string: fileName as! String)
        if let name = fileUrl?.deletingPathExtension().lastPathComponent {
            print(name)


            let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
            if (assetPath.absoluteString.hasSuffix("JPG")) {
                sonu = "JPG"
                print("JPG")
            }
            else if (assetPath.absoluteString.hasSuffix("PNG")) {
                sonu = "PNG"
                print("PNG")
            }
            else if (assetPath.absoluteString.hasSuffix("GIF")) {
                sonu = "GIF"
                print("GIF")
            }
            else {
                sonu = "Unknown"
                print("Unknown")
            }

            return name
        }
    }
    return ""

}

步骤4:在您想要的地方调用此方法。

 let strBase64 = imageDataForApi?.base64EncodedString()
    print(strBase64!)

答案 1 :(得分:1)

您需要先将字典形式的数据转换为json并将其发送到服务器 因此,请将此代码添加到api函数中。

func apiToSaveData(strURL: String)
    {
        let myURL = URL(string: strURL)
        let request = NSMutableURLRequest(url: myURL!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let token = "Bearer " + strToken

        request.setValue(token, forHTTPHeaderField: "Authorization")

        var postString: [String : String] = ["" : ""]

        if let navController = self.navigationController, navController.viewControllers.count >= 2
        {
            //Comes from After VerifyOTP after Returning Screen
            let viewController = navController.viewControllers[navController.viewControllers.count - 2]

            if viewController.restorationIdentifier == "VerifyOTP"
            {
                postString = ["image": strEncodedImg, "name": tfName.text!, "phone": tfMobile.text!, "email": tfEmail.text!, "otp": strOTP]

            }

            else if viewController.restorationIdentifier == "VisitorVC"
            {
                let imgObj = otlBtnTakeImage.imageView?.image
                let imgData: Data = UIImagePNGRepresentation(imgObj!)!
                let strEncodedImg1 = imgData.base64EncodedString()
                print("ENcodedImage: \(strEncodedImg1)")

               postString = ["image": strEncodedImg1, "name": tfName.text!, "phone": tfMobile.text!, "email": tfEmail.text!]
            }
        }

        do {
            // pass dictionary to nsdata object and set it as request body
            request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)

        } catch let error {
            print(error.localizedDescription)
        }

        let postTask = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in

        print(response!)

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("POST Method :\(json)")


                if dict["status"] as? String == "1"
                {

            }

        } catch let error {

            print(error.localizedDescription)
        }
    }
    postTask.resume()
}