使用POSTMAN在目录中上传图像

时间:2018-06-11 07:51:37

标签: php json api

在我的api中,我能够在xyz数据库的abc表中存储所有数据,如用户名,电子邮件,密码和imagepath,但图像没有出现在我的文件夹中。当我使用POSTMAN发送数据时,它显示'产品已创建'以及存储在我的数据库中的所有数据,但图像不会出现在我的文件夹中。它是我的第一个api,我是初学者,任何人都可以帮助我......

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '/formdatabase.php';

// instantiate product object
include_once '/formproduct.php';

$database = new Database();
$db = $database->getConnection();

$product = new Product($db);

// get posted data
$data = (object) $_POST;

// set product property values
$product->username = $data->username;
$product->email = $data->email;
$product->password = $data->password; 

//path were our avatar image will be stored
        $product->avatar = ('image/'.$_FILES['avatar']['name']);

        //make sure the file type is image
        if (preg_match("!image!",$_FILES['avatar']['type'])) {

            //copy image to images/ folder 
            if (copy($_FILES['avatar']['tmp_name'], $avatar)){



            }
            else {
                echo '{';
                    echo '"message": "File upload failed!"';
                echo '}';
            }

        }   
        else {
            echo '{';
                echo '"message": "Please only upload GIF, JPG or PNG images!"';
            echo '}';
        }



// create the product
if($product->create()){
    echo '{';
        echo '"message": "Product was created."';
    echo '}';
}

// if unable to create the product, tell the user
else{
    echo '{';
        echo '"message": "Unable to create product."';
    echo '}';
}
?>

1 个答案:

答案 0 :(得分:1)

复制文件时,请使用$avatar代替$product->avatar,这就是图片无法复制的原因。

应该是:

if (copy($_FILES['avatar']['tmp_name'], $product->avatar))

希望有所帮助