【问题标题】:Wordpress file upload Programmatically ErrorWordpress 文件上传程序错误
【发布时间】:2014-09-28 01:12:39
【问题描述】:

我在 Wordpress 中创建了一个静态页面。并希望在帖子中上传和附加图片(id 159),。但是以下代码不起作用。我在here找到了这段代码。

我的代码:

if(isset($_POST['submitbutton'])) 
{
$file = $_FILES["attachment"]["name"];
$parent_post_id = 159;
$filename = basename($file);
$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_parent' => $parent_post_id,
    'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
    'post_content' => '',
    'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
if (!is_wp_error($attachment_id)) {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
    wp_update_attachment_metadata( $attachment_id,  $attachment_data );
    }
  }
}

HTML 代码:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="attachment"/>
    <input type="submit" name="submitbutton" value="Vorschau">
</form> 

错误:

Warning: file_get_contents(Desert.jpg): failed to open stream: No such file or directory in D:\wamp\www\hossinger\wp-content\themes\hossinger\template-reports.php on line 81

【问题讨论】:

  • “不工作”是什么意思?有什么错误吗?
  • 警告:file_get_contents(Desert.jpg):无法打开流:D:\wamp\www\hossinger\wp-content\themes\hossinger\template-reports.php 中没有这样的文件或目录在第 81 行

标签: php wordpress upload


【解决方案1】:

你得到什么样的错误?在页面顶部添加error_reporting(E_ALL);,以查看脚本生成的所有警告和错误。

大多数情况下,使用这样的脚本,问题在于您尝试将上传文件移动到的文件夹的读/写权限。

编辑: 啊,我明白了;我认为问题在于您正在尝试上传 $_FILES 'name' 而不是 'tmp_name'。

改变:

$upload_file = wp_upload_bits($filename, null, file_get_contents($file));

到:

$upload_file = wp_upload_bits($filename, null, file_get_contents($_FILES["attachment"]["tmp_name"]));

【讨论】:

  • 上传文件夹对所有人都有读写权限(777)。还是不行。
  • 您是否将行从 $file 更改为 $_FILES["attachment"]["tmp_name"] ?您是否遇到另一个错误?
  • 非常感谢@Terwanerik。我是 wordpress 新手,丢了 3 小时。再次感谢您。
【解决方案2】:

尝试使用$_FILES["attachment"]["tmp_name"] 而不是$_FILES["attachment"]["name"]

$_FILES["attachment"]["name"] 在执行时服务器上不存在。当您上传文件时,PHP 将文件放置在具有(配置相关)随机名称的临时目录中,该文件存储在 $_FILES["attachment"]["tmp_name"] 中,并且是您需要引用才能移动的内容。

【讨论】:

  • 谢谢。我遵循@Terwanerik 解决方案。两个答案都是相同且有用的。
猜你喜欢
  • 2013-08-11
  • 2011-05-04
  • 2014-09-22
  • 2018-10-15
  • 2016-12-25
  • 2016-08-02
  • 2010-11-17
  • 2014-04-23
  • 2017-03-11
相关资源
最近更新 更多