如何正确显示上传的图像?

时间:2017-09-20 06:02:03

标签: wordpress plugins

我有Wordpress插件,其中我尝试显示上传的图像,但我得到这样的网址:

http://localhost/opt/lampp/htdocs/wordpress2/wp-content/plugins/fileuploadplugin/uploads/website-development-banner.jpg

而不是:

http://localhost/wordpress2/wp-content/plugins/fileuploadplugin/uploads/website-development-banner.jpg

我的代码是:

<?php
// Configuration - Your Options
$allowed_filetypes = array('.csv','.jpg','.gif','.png','.jpeg'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/wordpress2/wp-content/plugins' );
        //$targetpath=WP_PLUGIN_DIR.'/testplugin/documents/'.basename($_FILES["photo"]["name"]);
$upload_path = WP_PLUGIN_DIR.'/fileuploadplugin/uploads/'; // The place the files will be uploaded to (currently a 'files' directory).
//echo $upload_path;exit;
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
//$targetpath='/uploads'.basename($filename);

// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
    die('The file you attempted to upload is not allowed.');

// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
    die('The file you attempted to upload is too large.');

// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
    die('You cannot upload to the specified directory, please CHMOD it to 777.');

// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
    echo 'Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
else
    echo 'There was an error during the file upload.  Please try again.'; // It failed :(.   
?>

我的问题是如何从$ uploadpath中删除/opt/lampp/htdocs以使上传的图片正确显示?

1 个答案:

答案 0 :(得分:0)

问题是您使用相同的路径上传和显示图像。

上传图片的路径

在上面的上传代码中,您需要使用文件系统路径,就像您一样。代码中的路径是:

$upload_path = WP_PLUGIN_DIR.'/fileuploadplugin/uploads/'; // The place the files will be uploaded to (currently a 'files' directory).

这将具有类似于的值 /home/user/var/www/wp-content/plugins/fileuploadplugin/uploads/

显示图片的网址

文件系统路径显然无法显示图像,因此您需要使用相对于您网站的网址或路径,例如
http://www.example.com/wp-content/plugins/fileuploadplugin/uploads/uploadedimage.jpg

要获取插件文件夹的URL,您需要使用:

$upload_url = WP_PLUGIN_URL.'/fileuploadplugin/uploads/';

然后您可以使用该路径显示图像,例如

 <img src="/<?php echo $upload_url.$filename; ?>" />

注意:

我保留了WP_PLUGIN_DIR并在上面的代码中使用了WP_PLUGIN_URL,以便您更轻松地查看所需的更改。但是这些不应该直接使用。相反,您应该使用WP提供的函数来获取这些值:ref Wordpress Codex: Determining Plugin and Content Directories