Matt Kelly
Matt Kelly

Reputation: 1491

How to upload a UIImage to MySQL via PHP from Swift?

I have an app that uploads some data to a MySQL database via some PHP web services I wrote. I have got the text data to upload successfully, but I am struggling trying to get an image to upload. Basically, the user takes a photo using their iPhone camera, I convert it to a UIImage and now want to upload it.

I have looked at the following sources for help but they haven't seemed to work for me: How to Upload text, pdf, doc, zip file via PHP file upload to MySQL
https://www.youtube.com/watch?v=HqxeyS961Uk (The code in here wouldn't compile for me and I copied it letter for letter)
How to post a picture from iPhone app (in Swift) to MySQL database?
Saving image on db mysql through swift
Swift - uploading base64 encoded image to php and displaying the image
Getting a UIImage from MySQL using PHP and jSON

I want to upload the image and text together in the same query if possible, as they relate to one another and my MySQL table assigns an auto number for new rows.

Edit Thanks to the answers below. I am a little unsure as to how to implement the changes you guys suggested. My Swift code at the moment to upload text data is:

let url:NSURL = NSURL(string: "http://www.website.com.au/savenewexpense.php")!
        let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        var dataDictionary:[String:AnyObject] = ["Date" : strDate, "Staff" : strStaff, "Amount" : dblAmount, "Category" : strCategory]
        var data:NSData = NSJSONSerialization.dataWithJSONObject(dataDictionary, options: nil, error: nil)!
        request.HTTPBody = data

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

        let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in

            let response:[String:String] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String:String]
            if let result = response["result"] {
                if result == "success" {
                    NSLog("Text Data saved successfully")
                    if self.SendImageToServer() == true {
                        NSLog("Image Data saved successfully")
                        self.SaveSuccessful()
                    } else {
                        NSLog("Image Data failed to save")
                        self.DataFail()
                    }
                } else {
                    NSLog("Error saving data")
                    self.DataFail()
                }
            } else {
                NSLog("No response")
                self.NoResponse()
            }

        })

        task.resume()
    }

and my PHP code is:

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$json = file_get_contents('php://input');
$data = json_decode($json, true);

$stmt = $conn->prepare("INSERT INTO tblExpenses (Date, Staff, Amount, Category) VALUES (?, ?, ?, ?)");
$txtDate = $data['Date'];
$txtStaff = $data['Staff'];
$txtAmount = $data['Amount'];
$txtCategory = $data['Category'];
$stmt->bind_param("ssds", $txtDate, $txtStaff, $txtAmount, $txtCategory);
$stmt->execute();
echo '{"result" : "success"}';


$stmt->close();
$conn->close();

How should I implement the image into this?

Thanks

Upvotes: 2

Views: 2442

Answers (1)

Fatti Khan
Fatti Khan

Reputation: 1553

What you have to do is set the Boundary for the Image as an example use the code to Convert the NSDATA of image to the boundary values

if let dta = data as? NSData {
                bodyData.appendData(String(format:"\r\n--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
                bodyData.appendData(String(format:"Content-Disposition: form-data; name=\"photo\(i)\"; filename=\"image.png\"\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);
                bodyData.appendData(String(format:"Content-Type: image/png\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!);

                bodyData.appendData(dta);
            }

Here what you do is you set the image name and then the Image Data first you convert the data using allowLossyConversion and then send the POST data with the other data to service

request.HTTPBody = bodyData

just use this to send the image

Upvotes: 2

Related Questions