图片已上传到文件夹,但未显示-php上传图片

时间:2019-04-30 16:16:38

标签: php

我试图使用户从我的应用程序上传图像,并且试图将其上传到上载文件夹。我已经在下面显示了文件夹结构)。我可以将图像正确保存在相应的文件夹中,也可以将图像文件的名称存储到DB中,但是当我尝试将该图像显示到用户帐户中时,我无法使其可见。我想我弄乱了PATH。

文件夹结构:

  • htdocs
    • demo_app
      • 应用
        • 配置
          • config.php
        • 控制器
        • 核心
        • 观看次数
        • 模型
        • 上传
        • userImage
        • .htaccess
      • public(这是一个根文件夹)
        • 资产
          • css
          • js
          • 图片
          • 上传
          • userImage
        • index.php(这是一个根索引文件)
        • .htaccess
      • 供应商
      • .htaccess

因此,使用上述文件夹结构,我尝试了几件事:

  1. 将图像上传到userImage文件夹(app / uploads / userImage /),我能够将图像成功上传到此文件夹。但是当我尝试显示它时,我没有得到任何图像。

  2. 我还尝试过将图像上传并存储到userImage文件夹(/ public / assets / uploads / userImage /),但是这次我什至没有成功将其存储在文件夹中。

    < / li>

以下代码段均来自我的两次尝试。

config.php

<?php 

 $site_url = '/';
 define('SITE_URL', $site_url);
 define('APP_ROOT',dirname(dirname(__FILE__))); // (Path to 'app' folder)
 define('URL_ROOT', 'http://localhost/demo-app');

 // Following path is to upload image to public/assets/uploads/) folder
 define('UPLOAD_PATH', 
 dirname(dirname(dirname(__FILE__)))."/public/assets/uploads");

控制器(userController.php)

$img_name = $_FILES["image"]["name"];
$upload_folder = APP_ROOT . "/uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);

// The above uploading code works perfect for me to upload the image to app/uploads/userImage/ folder

// Following code doesn't work for me to upload it to the public/assets/uploads/userImage folder
 //Approach 2

 $upload_folder = UPLOAD_PATH . "/userImage/" . $img_name;
 move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);

**查看(index.php)**(app / views / users / index.php)

// Following for showing image from app uploads folder

  <?php $img_path = APP_ROOT . "/uploads/userImage/" . $user->image ?>
  <img src="<?php echo $img_path; ?>">

// Following for showing image from public uploads folder

  <?php $img_path = URL_ROOT . "/assets/uploads/userImage/" . $user->image ?>
  <img src="<?php echo $img_path; ?>">

我认为PATH存在问题,因此,如果有人可以帮助我,那将很棒。预先欣赏。

1 个答案:

答案 0 :(得分:0)

假设文件userController.php位于controllers文件夹内。将您的第一部分更改为

$img_name = $_FILES["image"]["name"];
$upload_folder = "../uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);

,然后将第二条路径更改为

$upload_folder = "../../public/assets/uploads/userImage/" . $img_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $upload_folder);

为了显示,您的文件位于app/views/users/index.php中,因此

<?php $img_path = "../../uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">

<?php $img_path = URL_ROOT . "/assets/uploads/userImage/" . $user->image ?>
<img src="<?php echo $img_path; ?>">