1

I've recently been attempting to send an image from iOS to a PHP file, then save said image to the disk and add the path to the database. I believe that my NSURLSession for uploading the image to the PHP file is working, but don't hold me to that, as I'm not positive. Even then, I'm not exactly sure how I would be able to access the file and save it to the disk.

I'm under the impression that this code should return the file meta data to iOS if it is working correctly, don't hold me to this, I'm still not quite sure how $_FILE works, yet I'm not receiving anything, so I'm led to assume that one, I'm not accessing it correctly, or two, I haven't uploaded it correct.

<?php

error_reporting(E_ALL);
ini_set('display errors', 1);

$arr = array('name' => $_FILES['profile_img']['name'], 'type' => $_FILES['profile_img']['type'], 'size' => $_FILES['profile_img']['size']);

echo json_encode($arr);

?>

Here's the URLSession, just for good measure - like I said, I'm not positive if this truly works like I think it does.

func uploadImage(image: UIImage) {
    var url: NSURL = NSURL(string: "https://example.com/uploadPicture.php")!
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request.HTTPMethod = "POST"

    var imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))

    var boundary = NSString(format: "---------------------------14737809831466499882746641449")
    var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
    println("Content Type \(contentType)")
    request.addValue(contentType, forHTTPHeaderField: "Content-Type")

    var body = NSMutableData.alloc()

    // Title
    body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

    // Image
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData)
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body

    let task = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()).dataTaskWithRequest(request) {
        data, response, error in

        if (error != nil) {
            println("Error Submitting Request: \(error)")
            return
        }

        var err: NSError?
        var userData: [String: String]!
        userData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [String: String]

        if(userData != nil) {
            println(userData)
        } else {
            println("No data recieved.")
        }
    }

    task.resume()


}

I'd like to note, Alamofire is out of the question at the moment. I'd like to do this myself, and to my knowledge, it currently doesn't support multipart requests.

EDIT: After some extensive debugging (and help from NSChat!) I was able to find where the program fails. It lands in the block of code below. I quite frankly have no idea what this block does, so if someone can explain, please, do.

    var boundary = NSString(format: "---------------------------14737809831466499882746641449")
    var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
    println("Content Type \(contentType)")
    request.addValue(contentType, forHTTPHeaderField: "Content-Type")
    request.timeoutInterval = 60

    var body = NSMutableData()

    // Title
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

    // Image
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData)
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body
Jeffrey
  • 1,271
  • 2
  • 15
  • 31

0 Answers0