Search code examples
phpswiftalamofirealamofireimage

Image Upload doesn't work with swift alamofire and php


After trying different approaches, I couldn't find the cause of the issue...

I'm trying to upload an image (choosen from photo library) to store it on a linux webserver using a php script.

Here the Swift 4 code:

func uploadImage(imageFile: UIImage?){

    let imageData = UIImageJPEGRepresentation(imageFile!, 0.5)!

    Alamofire.upload(
        multipartFormData: { multipartFormData in

            multipartFormData.append(imageData, withName: "image", fileName: "test", mimeType: "image/jpg")

        },
        to: "http://XXX/images/upload.php", method: .post,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let result = response.result.value {
                        // Get the json response. From this, we can get all things we send back to the app.
                        //let JSON = result as! NSDictionary
                        //self.imageServerLocation = JSON.object(forKey: "filepath") as? String
                        debugPrint(response)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )
}

The code at the server where is the following:

<?php
if (empty($_FILES["image"])) {
    // So we send a message back saying there is no data...
    $response = array("error" => "nodata");
}else { // If there is data
    $response['error'] = "NULL";
    // Setup a filename for the file. Uniqid can be changed to anything, but this makes sure
    // that every file doesn't overwrite anything existing.
    $filename = uniqid() . ".jpg";
    // If the server can move the temporary uploaded file to the server
    if (move_uploaded_file($_FILES['image']['test'], '/default/' . $filename)) {
        // Send a message back saying everything worked!
        // I also send back a link to the file, and the name.
        $response['status'] = "success";
        $response['filepath'] = "https:" . $filename;
        $response['filename'] = "".$_FILES["file"]["name"];
    } else{
        // If it can't do that, Send back a failure message, and everything there is / should be form the message
        // Here you can also see how to reach induvidual data from the image, such as the name.
        $response['status'] = "Failure";
        $response['error']  = "".$_FILES["image"]["error"];
        $response['name']   = "".$_FILES["image"]["name"];
        $response['path']   = "".$_FILES["image"]["tmp_name"];
        $response['type']   = "".$_FILES["image"]["type"];
        $response['size']   = "".$_FILES["image"]["size"];
    }
}
// Encode all the responses, and echo them.
// This way Alamofire gets everything it needs to know
echo json_encode($response);
?>

I get always the same error:

[Data]: 107 bytes
[Result]: SUCCESS: {
    error = 0;
    name = test;
    path = "/tmp/php7iIqSv";
    size = 43337;
    status = Failure;
    type = "image/jpg";
}

Can someone give me a hint to solve my problem?

Thanks in advance


Solution

  • I think you have error in move_uploaded_file function.You are giving key that is not there in $_FILES global

    It should be like move_uploaded_file($_FILES['image']['tmp_name'], '/default/' . $filename)

    And make sure the folder/directory where you are moving the file is writable.