从前端上传自定义功能图片仅上传文件夹名称

时间:2017-11-02 16:15:37

标签: php jquery ajax wordpress file-upload

感谢您查看我的问题。

问题

我需要能够使用与帖子相关联的上传功能图片(缩略图),正在处理的网站能够从网站的前端发帖。

实施自定义代码

在帖子提交表单中,我使用的是file类型的输入元素:

<form class="compose-post-form" method="POST" enctype="multipart/form-data">

  ...

 <input type="file" name="featured" id="featured">

 ...


</form>

数据通过jQuery AJAX发送到表单提交后端:

$.ajax({
  type: 'post',
  url: t_ajax_url.ajax_url,
  data: $this.serialize() + "&tri_post_content="+article_content+"&article="+article,
  beforeSend: function () {
    is_sending = true;
  },
  success: function (data) {
    //window.location.replace(get_homepage_url+'trisine');

    var fd = new FormData();
    var file = $('#featured').val();
    fd.append("featured", file);
    fd.append('action', 'thumbnail_up');

    jQuery.ajax({
        type: 'POST',
        url: t_ajax_url.ajax_url,
        data: fd,
        contentType: false,
        processData: false,
        success: function(response){
            console.log(response);
        }
    });
  },
  error: function(xhr, status, error) {
    console.log(status);
  }
});

这是保存缩略图的代码,现在我只是测试帖子ID为22:

  add_action( 'wp_ajax_thumbnail_up', 't_thumbnail_up' );
  function t_thumbnail_up(){

    $uploaddir = wp_upload_dir();
    $file = $_FILE['featured'];

    $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );
    move_uploaded_file( $file['tmp_name'] , $uploadfile );
    $filename = basename( $uploadfile );

    $wp_filetype = wp_check_filetype(basename($filename), null );

    $attachment = array(
      'post_mime_type' => $wp_filetype['type'],
      'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
      'post_content' => '',
      'post_status' => 'inherit',
      'menu_order' => $_i + 1000
      );
    $attach_id = wp_insert_attachment( $attachment, $uploadfile );

    update_post_meta(22, '_thumbnail_id',$attach_id);
    set_post_thumbnail( 22, $thumbnail_id );

    exit();
  }

结果是上传了一些内容,但似乎只是文件夹名称,即11月份的月号,该文件夹实际上并未在服务器上创建:

item available in Media Library menu

任何有关如何使其发挥作用的帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

使用此功能处理来自ajax的文件。

<?php
$thumbnail = $_FILES[ 'featured' ];
$thumbnail_id = media_handle_sideload( $thumbnail, $post_id );
set_post_thumbnail( $post_id, $screenshot_id );