iOS Upload Image from Gallery or Camera to Server Side

On October 28, 2015, in Other Online Technology, by James Liu

Today, one of my friends asked me how to select photos from gallery and upload it to server in iPhone. I think it is much helpful to write a tutorial with example source code, instead of asking him to google the solution. To make sure that my example works properly (it always works properly though), I will write a server side function which accepts the upload images. The server side functions will be implemented by PHP, a very simple script language. After that, I will write another tutorial for upload images from gallery or camera in iPhone and iPad.

In this tutorial, I will start from the simplest case. Then, I will make the script more complicated. First, let’s talk about uploading a file and save it on server.

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

The above php script will make a folder to save the uploading file, if the folder doesn’t exist. Then, it will save the incoming file to this folder.

Ok, now I will make it more complicated. As this tutorial is talking about how to upload photos to server from iPhone. So we need to set some constrains such as the incoming files must be images. Let’s see the example source code version 2:

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);

    if(!(getimagesize($_FILES["fileToUpload"]["tmp_name"]) !== false)) {
        echo "Sorry, your image is invalid";
        exit;
    }

    $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));
    if($imageFileType != "jpg"
            && $imageFileType != "png"
            && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

Great! In above php example source code, we successfully add two constrains to detect the incoming files are real images. If you want to limit the incoming file’s size smaller than 2M, you can add another constrain:

<?php //ignore this comment >
    $uploadFolder = "./upload";
    if (!file_exists($uploadFolder)) {
        mkdir($uploadFolder);
    }
    
    $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"]);

    if(!(getimagesize($_FILES["fileToUpload"]["tmp_name"]) !== false)) {
        echo "Sorry, your image is invalid";
        exit;
    }

    $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));
    if($imageFileType != "jpg"
            && $imageFileType != "png"
            && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    if ($_FILES["fileToUpload"]["size"] > 2000000) {
        echo "Sorry, your file is too large.";
        exit;
    }

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $uploadFile)) {
        echo "Successfully";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

Test Upload Script with HTML FORM

The mechanism of selecting and uploading image to server is the same as submitting a form in html. To test above PHP script, we can simply create following test case:

<html>
    <head>
        <title>PHP Upload Test</title>
    </head>
    <body>
        <form action="http://192.168.31.105/uploadimage.php" method="post" enctype="multipart/form-data">
            <input type="file" name="fileToUpload" />
            <input type ="hidden" name="partyGroupId" id="partyGroupId" value="10050"/>
            <input type="submit" name="submit" value="Click to Upload"/>
        </form>
    </body>
</html>

Select and Upload Multiple Photos from iPhone

The above example only shows you how to handle one image uploading. However, the real use case is more complicated than that. In most popular iOS apps, they allow users to select and upload multiple photos at once. To support this scenario, we need to change the above PHP example source code a little bit.

<?php  //ignore this comment >
$uploadFolder = "./upload";
if (!file_exists($uploadFolder)) {
    mkdir($uploadFolder);
}

if (is_array($_FILES["fileToUpload"])) {
    $numberOfFiles = count($_FILES["fileToUpload"]["name"]);
    for ($i = 0; $i < $numberOfFiles; $i++) { //ignore this comment >
        $uploadFile = $uploadFolder . "/" . basename($_FILES["fileToUpload"]["name"][$i]);
        $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));

        if (!(getimagesize($_FILES["fileToUpload"]["tmp_name"][$i]) !== false)) {
            echo "Sorry, your image is invalid";
            exit;
        }

        if ($_FILES["fileToUpload"]["size"][$i] > 10000000) {
            echo "Sorry, your file is too large.";
            exit;
        }

        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            exit;
        }

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $uploadFile)) {
            echo "Upload image ".basename($_FILES["fileToUpload"]["name"][$i])." successfully!";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

How to Test Above PHP Script for Selecting and Uploading Multiple Images from iPhone

Before we start to build the iPhone app to select and upload multiple images, let’s make sure that our backend application is able to accept multiple images uploading. Again, we can use HTML form to simulate this action. Here is a test case to select and upload two images at once. You can add more images by adding more input tag in the html form.

<html>
    <head>
        <title>PHP Upload Test</title>
    </head>
    <body>
        <form action="http://192.168.31.105/uploadimage.php" method="post" enctype="multipart/form-data">
            <input <!->-->
type="file" name="fileToUpload[]" />
            <input <!->-->
type="file" name="fileToUpload[]" />
            <input type ="hidden" name="partyGroupId" id="partyGroupId" value="10050"/>
            <input type="submit" name="submit" value="Click to Upload"/>
        </form>
    </body>
</html>

As we assign the name=”fileToUpload[]” in each input tag, the server side will treat the incoming fileToUpload variable contains several files. Therefore, the php script will use for loop to save every uploaded image.

 

8 Responses to “iOS Upload Image from Gallery or Camera to Server Side”

  1. Akshay Ambekar says:

    Hi…. Thanks for the multiple image upload code…
    But now I want to upload multiple videos.. so which are the changes need to do in php?
    In iOS I will send nsdata of video but how to haldle it in Php?

    Thanks

  2. How to add this code in my project.

  3. rusy hand says:

    Hi, downloaded your files… can’t seem to get it to work. it says its successful uploading… however i look in my ftp in filezilla… and no images are there :/

    • James Liu says:

      You’d better to check the code. I copy the example code from my project. BTY, my current example code is for uploading images. I have set some constrain in the code.

      • rusy hand says:

        I checked the code. What constraints do you mean? It creates the folder in my server. I can see the mkdir function… however doesn’t put the image in it :/ what constraints are you talking about?

        • James Liu says:

          Do you have any PHP programming background? If yes, it will be a very simple case to debug and find the solution. If no, please study the basic PHP programming first. Here I give you some tips about how to debug and find the problem:
          1. check $_FILES[“fileToUpload”] value
          2. check your image size
          3. check your image extension, only lower case .jpg, .png, .jpeg, gif supported.

Leave a Reply

WordPress Blog

WordPress Themes