9

I'm trying to upload 3 images to the server from iOS to my PHP service. For some reason the folder remains empty after posting, but the rest of the data goes through and gets persisted into mysql.

My iOS code:

Alamofire.upload(.POST, urlString, multipartFormData: {
            multipartFormData in

            if (firstPhoto != nil) {
                if  let firstImageData = UIImageJPEGRepresentation(firstImage!, 0.6) {
                    print("uploading image");
                    multipartFormData.appendBodyPart(data: firstImageData, name: "firstImage", fileName: "firstImage.png", mimeType: "image/png")
                }
            }

            if (secondPhoto != nil) {
                if  let secondImageData = UIImageJPEGRepresentation(secondImage!, 0.6) {
                    print("uploading image");
                    multipartFormData.appendBodyPart(data: secondImageData, name: "secondImage", fileName: "secondImage.png", mimeType: "image/png")
                }
            }

            if (thirdPhoto != nil) {
                if  let thirdImageData = UIImageJPEGRepresentation(thirdImage!, 0.6) {
                    print("uploading image");
                    multipartFormData.appendBodyPart(data: thirdImageData, name: "thirdImage", fileName: "thirdImage.png", mimeType: "image/png")
                }
            }


            if  let imageData = UIImageJPEGRepresentation(firstImage!, 0.6) {
                print("uploading image");
                multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
            }

            if  let imageData = UIImageJPEGRepresentation(firstImage!, 0.6) {
                print("uploading image");
                multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png")
            }


            for (key, value) in parameters {
                multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }

            }, encodingCompletion: {
                encodingResult in

                switch encodingResult {
                case .Success(let upload, _, _):
                    print("Запрос отправлен")
                    upload.responseJSON { response in
                        print(response.request)  // original URL request
                        print(response.response) // URL response
                        print(response.data)     // server data
                        print(response.result)   // result of response serialization

                        if let JSON = response.result.value {
                            print("JSON: \(JSON)")
                        }
                        completion(response.result.value)
                    }

                case .Failure(let encodingError):
                    print(encodingError)
                    completion(nil)
                }
        })

}

On my PHP I'm not sure if I'm missing anything here:

 <?php

require_once 'Functions/common_functions.php';
require_once 'Functions/engine.php';
require_once 'Functions/json.php';
require_once 'Functions/check_token.php';

if (count($_REQUEST) == 6) {
    foreach($_REQUEST as $k => $v) {
        if (strlen($k) > 0 && strlen($v) > 0) {
            $_REQUEST[$mysqli->real_escape_string($k)] = $mysqli->real_escape_string($v);
        } else {
            die(errorJSON("Empty parameter", "666"));
        }
    }

    $userID = checkAccessToken($_REQUEST['access_token'], $mysqli);

    if ($userID == 0) {
        die(errorJSON("Incorrect access token", "666"));
    }

    $mysqli->query('INSERT INTO Book (title, authorID, detail, price, categoryID, conditionText) VALUES ("'.$_REQUEST['title'].'", "'.$userID.'", "'.$_REQUEST['detail'].'", "'.$_REQUEST['price'].'", "'.$_REQUEST['categoryID'].'", "'.$_REQUEST['condition'].'")');

    $insertID = $mysqli->insert_id;

    if ($insertID > 0) {
        savePhotos($mysqli, $insertID);
        $message = book($insertID, $userID, $mysqli);
        die(successJSON($message));
    } else {
        die(errorJSON("Failed insert book in database", "666"));
    }
} else {
    die(errorJSON("Incorrect count of parameter" .  count($REQUEST) . count($_POST), "666"));
}

function savePhotos($mysqli, $bookID) {
    if(!is_dir('/home/thebakpa/resources/book_photos/')) {
        mkdir('/home/thebakpa/resources/book_photos/', 0777, true);
    }
    try {
        $uploaddir = '/home/thebakpa/resources/book_photos/';
        $file = $_FILES['userfile']['photo1'];

        if ($file != 0) {
            $uploadfile = $uploaddir . $file;

            $name = "photo1-".$bookID;
            $photoPath = '/home/thebakpa/resources/book_photos/'.$name.'.jpg';

            $mysqli->query('UPDATE Book SET photo1='.$photoPath.' WHERE bookID='.$bookID.'');
            move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
        }

        $file = $_FILES['userfile']['photo2'];

        if ($file != 0) {
            $uploadfile = $uploaddir . $file;

            $name = "photo2-".$bookID;
            $photoPath = '/home/thebakpa/resources/book_photos/'.$name.'.jpg';

            $mysqli->query('UPDATE Book SET photo1='.$photoPath.' WHERE bookID='.$bookID.'');
            move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
        }

        $file = $_FILES['userfile']['photo3'];

        if ($file != 0) {
            $uploadfile = $uploaddir . $file;

            $name = "photo3-".$bookID;
            $photoPath = '/home/thebakpa/resources/book_photos/'.$name.'.jpg';

            $mysqli->query('UPDATE Book SET photo1='.$photoPath.' WHERE bookID='.$bookID.'');
            move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);
        }
    } catch(Exception $ex){
        echo "ERROR:".$ex->GetMessage()."\n";
        exit(1);
    }
}
?>
Bista
  • 7,869
  • 3
  • 27
  • 55
franklinexpress
  • 1,149
  • 14
  • 44
  • I really like this question. Just found it with 35 minutes left on the bounty timer. I notice none of your answers have up-votes. Please notify me if it goes up for bounty again and is unsolved. I'd like to build a solution around your posted code with a little more time. Should add, I will solve with out bounty. – Dave Thomas Sep 13 '16 at 06:15
  • 1
    i think the user posted the question is not active on this question. Because my answer is correct and i have tried with sample code also but no response. – Mahesh Agrawal Sep 13 '16 at 06:17
  • Cool I was just reading yours. I up voted it earlier... but then stopped myself because I hadn't tested it. I'll give you the up vote ;) Looks correct. – Dave Thomas Sep 13 '16 at 06:19
  • thanks, its my pleasure if my answer help someone. – Mahesh Agrawal Sep 13 '16 at 06:23
  • /giphy high five ( if only it worked here ) – Dave Thomas Sep 13 '16 at 06:24
  • I'm active guys and gals, I've been busy working on some android stuff, I'm not a PHP dev nor iOS dev, just messing with a project. I'll get to this in the next day or two – franklinexpress Sep 14 '16 at 15:42
  • it happens...always here to help...any problem..just comment below.. – Mahesh Agrawal Sep 14 '16 at 17:45

3 Answers3

7

Problem is in your savePhotos function of PHP source. Also some extra code written in iOS code. I have removed extra code. Try once.

Here is the iOS code updated

Alamofire.upload(.POST, urlString, multipartFormData: {
        multipartFormData in

        if (firstPhoto != nil) {
            if  let firstImageData = UIImagePNGRepresentation(firstImage!, 0.6) {
                print("uploading image");
                multipartFormData.appendBodyPart(data: firstImageData, name: "firstImage", fileName: "firstImage.png", mimeType: "image/png")
            }
        }

        if (secondPhoto != nil) {
            if  let secondImageData = UIImagePNGRepresentation(secondImage!, 0.6) {
                print("uploading image");
                multipartFormData.appendBodyPart(data: secondImageData, name: "secondImage", fileName: "secondImage.png", mimeType: "image/png")
            }
        }

        if (thirdPhoto != nil) {
            if  let thirdImageData = UIImagePNGRepresentation(thirdImage!, 0.6) {
                print("uploading image");
                multipartFormData.appendBodyPart(data: thirdImageData, name: "thirdImage", fileName: "thirdImage.png", mimeType: "image/png")
            }
        }

        for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }

        }, encodingCompletion: {
            encodingResult in

            switch encodingResult {
            case .Success(let upload, _, _):
                print("Запрос отправлен")
                upload.responseJSON { response in
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization

                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
                    }
                    completion(response.result.value)
                }

            case .Failure(let encodingError):
                print(encodingError)
                completion(nil)
            }
    })

}

And here is the PHP code

function savePhotos($mysqli, $bookID) {
    $basePath = '/home/thebakpa/resources/book_photos/'
    if(!is_dir($basePath)) {
        mkdir($basePath, 0777, true);
    }
    try {
        $file1 = $_FILES['firstImage'];

        if (is_uploaded_file($file1['tmp_name'])) {
            $photoPath = $basePath.'photo1-'.$bookID.'.jpg';

            if (move_uploaded_file($file1['tmp_name'], $photoPath)) {
                $mysqli->query('UPDATE Book SET photo1='.$photoPath.' WHERE bookID='.$bookID.'');
            }
        }

        $file2 = $_FILES['secondImage'];

        if (is_uploaded_file($file2['tmp_name'])) {
            $photoPath = $basePath.'photo2-'.$bookID.'.jpg';

            if (move_uploaded_file($file2['tmp_name'], $photoPath)) {
                $mysqli->query('UPDATE Book SET photo2='.$photoPath.' WHERE bookID='.$bookID.'');
            }
        }

        $file3 = $_FILES['thirdImage'];

        if (is_uploaded_file($file3['tmp_name'])) {
            $photoPath = $basePath.'photo3-'.$bookID.'.jpg';

            if (move_uploaded_file($file3['tmp_name'], $photoPath)) {
                $mysqli->query('UPDATE Book SET photo3='.$photoPath.' WHERE bookID='.$bookID.'');
            }
        }
    } catch(Exception $ex){
        echo "ERROR:".$ex->GetMessage()."\n";
        exit(1);
    }
}
Mahesh Agrawal
  • 3,348
  • 20
  • 34
1

The names do not match ['userfile']['photo1'] in your php. But on the iOS side userfile and photo1 are never used. Try using $_FILES['firstImage']

svn
  • 1,235
  • 10
  • 22
1

try this if you submit image in json format(repeat same code for other images by chnaging image name)

<?php       

            $image          = $file;
            $directorypath1 = $uploaddir;
            $img            = str_replace('data:image/PNG;base64,', '', $image);
            $img            = str_replace(' ', '+', $img);
            $data           = base64_decode($img);
            $name           = rand() . '_' . time() . ".jpg";
            $img_path       = $directorypath1 . $name;
            file_put_contents($img_path, $data);

?>
Guri
  • 83
  • 8