iOS使用Alamofire上传PHP文件

9

我正在尝试从iOS上传3张图片到我的PHP服务端。但是在上传后,文件夹总是保持为空的状态,但其他数据可以成功传输并保存到mysql数据库中。

iOS代码如下:

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)
                }
        })

}

我的PHP代码中,我不确定是否有遗漏:

 <?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);
    }
}
?>

我非常喜欢这个问题。在赏金计时器还剩35分钟的时候才发现它。我注意到你的回答都没有得到赞同。如果再次被提出并且未解决,请通知我。我想利用更多时间基于你发布的代码构建一个解决方案。另外,我会在没有赏金的情况下解决这个问题。 - Dave Thomas
1
我认为提问的用户已经不再关注这个问题了。因为我的答案是正确的,我也尝试过使用示例代码,但没有得到回应。 - Mahesh Agrawal
很酷,我刚刚在看你的帖子。我之前已经点赞了...但是后来停下来因为我还没有测试过它。我会给你点赞的 ;) 看起来没问题。 - Dave Thomas
谢谢,如果我的回答能帮助到某人,我会很高兴。 - Mahesh Agrawal
/giphy 拍手致意(如果这里能用的话) - Dave Thomas
显示剩余2条评论
3个回答

7

问题出现在您的PHP源代码中的savePhotos函数上。此外,iOS代码中还写了一些额外的代码。我已经删除了额外的代码,请再试一次。

以下是更新后的iOS代码

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)
            }
    })

}

以下是 PHP 代码

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);
    }
}

非常感谢。 - franklinexpress
if(!is_dir($basePath)) {这里出现了语法错误,可以忽略吗? - franklinexpress

1
名称不匹配,即在您的php中 ['userfile']['photo1'] 与iOS侧未使用 userfilephoto1。请尝试使用$_FILES['firstImage']

1

如果您以JSON格式提交图像,请尝试此方法(通过更改图像名称为其他图像,重复相同的代码)。

<?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);

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接