【问题标题】:converting the image into Base64 code (Status code is 500) [closed]将图像转换为 Base64 代码(状态代码为 500)[关闭]
【发布时间】:2018-03-19 05:21:33
【问题描述】:

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

错误:

<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.

我的代码是:

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!]
            }
        }
}

【问题讨论】:

  • 甚至没有人知道您如何将图像对象转换为 base64 字符串对象。
  • 请问怎么把图片转成base64传给服务器
  • 500 个错误可能意味着问题出在服务器端,如果请求格式错误,您应该会收到 4XX 错误。

标签: ios swift api base64


【解决方案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()
}

【讨论】:

    【解决方案2】:

    我给你一个完整的解决方案,试试看。

    第 1 步:声明全局变量。

    var imageDataForApi:Data!
    

    第二步:把这段代码放到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 步:粘贴这个函数来打击 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!)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 2011-05-04
      • 1970-01-01
      • 2023-03-11
      • 2013-12-17
      • 2018-10-22
      相关资源
      最近更新 更多