nextstep
nextstep

Reputation: 1460

Swift POST Request (Base64 Image) to PHP Script

After reading through numerous similar questions I still don't understand what the problem is here.

I'm trying to send a Base64 encoded image to a simple PHP script, here's my Swift code:

func sendImage(encodedImage: String) {
    let url = URL(string: "http://www.site.whatever/image_upload.php")
    var request = URLRequest(url: url!)
    let postString = "encoded_image=\(encodedImage)"
    let postData = postString.data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
    request.httpBody = postData
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in
        if error != nil {
            // Handle error
            return
        }
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print(responseString)
    }
    task.resume()
}

Simple PHP Script

$request_method = $_SERVER["REQUEST_METHOD"];

switch ($request_method) {
    case 'POST':
        if (isset($_POST["encoded_image"])) {
            // POST parameter has been set successfully
            $return = ["POSTSET?" => "Yes"];
            echo json_encode($return);
        }
    // POST parameter was not set
    $return = ["POSTSET" => "No"];
    echo json_encode($return);
}

Problem:

With

let postString = "encoded_image=\(encodedImage)"

Where encodedImage is set with:

let encodedImage = image.pngData()!.base64EncodedString()

it returns {"POSTSET?","No"} // POST was not sent

With

let postString = "encoded_image=some_random_string"

it returns {"POSTSET?","Yes"} // POST sent successfully


I don't know why it works perfectly until I try and send a Base64.

Thoughts:

Is request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") the correct content type?

Should I be setting a content length since the Base64 string is so long?

Should request.httpBody be encoded using something other than String.Encoding.utf8?

Should my PHP be expecting something different to what Swift is sending?

Any insight would be helpful, thanks.

Upvotes: 0

Views: 1225

Answers (1)

nextstep
nextstep

Reputation: 1460

The string length I was seeing for a Base64 encoded PNG was around 12 million characters on average. The server on which the PHP script is running isn't capable of accepting the request and would result in an error.

I sent a JPG to the API instead, the Base64 string is closer to 3 million when sent like this.

let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let imageData = image.jpegData(compressionQuality: 1)!
let encodedImage = imageData.base64EncodedString()

This successfully sends the image, allowing me to decode and save on the back end.

Upvotes: 1

Related Questions