【问题标题】:Wordpress and AJAX - Upload image as featuredWordpress 和 AJAX - 上传特色图片
【发布时间】:2016-08-14 12:20:40
【问题描述】:

我在前端表单中使用带有 ajax 的 wordpress,我需要支持处理和上传特色图片。我的问题特别是关于特色图片。我的 html 是这样的:

<form id="msform" action="#" method="post" enctype="multipart/form-data">
//inputs of various nature
<input type="file" name="main_image" id="main_image"  multiple="false" value="" accept=".png, .jpg, .jpeg, .gif"/>
<input type="submit" class="submit" value="Publish"/>
</form>

我通过这个 jquery 将数据发送到一个 php 函数(遵循 Wordpress 方法):

function apfaddpost() {
    var formData = $('#msform').serialize();
    formData.append('main_image', $('#main_image')[0].files[0]); //here should be the problem
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: formData + '&action=apf_addpost', //here I send data to the php function calling the specific action
        processData: false,
        contentType: false

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

我的函数php类似于

function apf_addpost() {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    $file_handler = 'main_image';
    $attach_id = media_handle_upload($file_handler,$pid );
    update_post_meta($pid,'_thumbnail_id',$attach_id);
}

重要的是:标题、描述、标签等所有其他数据都已正确序列化和发送。问题在于图像。我也尝试过使用$_FILES[] 处理程序但没有成功,我想我的ajax 代码那时不是很好。你能帮助我吗?如果您对此问题有任何其他解决方法,请分享!提前致谢。

[已解决] 编辑

感谢下面的答案,我刚刚将我的 ajax 更改为

function apfaddpost() {
    var fd = new FormData($('#msform')[0]);
    fd.append( "main_image", $('#main_image')[0].files[0]);
    fd.append( "action", 'apf_addpost');      
   //Append here your necessary data
    jQuery.ajax({
        type: 'POST',
        url: apfajax.ajaxurl,
        data: fd, 
        processData: false,
        contentType: false,

        success: function(data, textStatus, XMLHttpRequest) {
            var id = '#apf-response';
            jQuery(id).html('');
            jQuery(id).append(data);
            resetvalues();
        },

        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }

    });
}

我发现FormData() 允许序列化文件,而.serialize() 方法则不允许。众所周知,继续前进很简单。 谢谢。

【问题讨论】:

    标签: php jquery ajax wordpress image-processing


    【解决方案1】:

    请尝试:

    我已经修改了你的代码。

    Jquery(添加了 FormData() 和追加)

    function apfaddpost() {
        var fd = new FormData();
        fd.append( "main_image", $('#main_image')[0].files[0]);
        fd.append( "action", 'apf_addpost');      
       //Append here your necessary data
        jQuery.ajax({
            type: 'POST',
            url: apfajax.ajaxurl,
            data: fd, 
            processData: false,
            contentType: false
    
            success: function(data, textStatus, XMLHttpRequest) {
                var id = '#apf-response';
                jQuery(id).html('');
                jQuery(id).append(data);
                resetvalues();
            },
    
            error: function(MLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
    
        });
    }
    

    function.php

    我已经添加了文件上传代码

    /******FILE UPLOAD*****************/
    function upload_user_file( $file = array() ) {    
        require_once( ABSPATH . 'wp-admin/includes/admin.php' );
        $file_return = wp_handle_upload( $file, array('test_form' => false ) );
        if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
            return false;
        } else {
            $filename = $file_return['file'];
            $attachment = array(
                'post_mime_type' => $file_return['type'],
                'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
                'post_content' => '',
                'post_status' => 'inherit',
                'guid' => $file_return['url']
            );
            $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
            wp_update_attachment_metadata( $attachment_id, $attachment_data );
            if( 0 < intval( $attachment_id ) ) {
              return $attachment_id;
            }
        }
        return false;
    }
    

    现在在function.php

    中修改你的函数apf_addpost()
    function apf_addpost() {
         foreach( $_FILES as $file ) 
         {  
              if( is_array( $file ) ) {
                    $attach_id =upload_user_file();  //Call function 
                    update_post_meta($pid,'_thumbnail_id',$attach_id);
              }
         }
    
    }
    

    【讨论】:

    • 谢谢@vrajesh!你解决了我的问题。我不知道 FormData() 允许序列化文件。我是 Jquery / Ajax 的初学者。再次感谢!
    【解决方案2】:

    对于 WordPress 中的 ajax 上传,需要注意以下几点;

    HTML

    对于发送图像,formenctype="multipart/form-data" 是必需的。 enctype 属性指定表单提交期间表单数据的编码方式。默认情况下它的application/x-www-form-urlencoded,因为我们正在上传文件,我们将值更改为multipart/form-data

      <form action="" method="post" enctype="multipart/form-data">
          <input type="file" id="image_upload">
          <button type="button" id="image_upload_btn">Update</button>
      </form>
    

    AJAX

    $("#image_upload_btn").click(function (e) {
      e.preventDefault();
      var fd = new FormData();
      var files = $("#image_upload")[0].files;
      fd.append("file", files[0]);
      fd.append("action", "upload_image"); // your ajax function
    
      if (files.length > 0) {
        jQuery.ajax({
          type: "POST",
          url: ajax_url, //  var ajax_url = " <?= admin_url('admin-ajax.php'); ?>"; pass it in the php file
          processData: false,
          contentType: false,
          data: fd,
          beforeSend: function () {
    // Any code you like
          },
          success: function (response) {
    // Success code
          },
          error: function (request, status, error) {
            console.log(error);
            alert(request.responseText);
          },
        });
      }
    });
    

    我们需要使用FormData() 接口来构造一组键/值对来表示我们的表单字段和值(这里是我们的图像文件)。这有助于使用 ajax 轻松传输文件。

    由于我们使用的是 WordPress,除了图像文件之外,我们还添加了 action 参数以及 FormData()

    这里要注意的另一件重要事情是processDatacontentType,没有它们您可能会遇到Uncaught TypeError: Illegal invocation

    1. 为什么是processData

    默认情况下,作为对象在 data 选项中传递的数据被处理并转换为 ajax 的查询字符串,因为我们正在执行文件上传,所以我们希望它为 false。

    1. 为什么是contentType

    默认情况下,application/x-www-form-urlencoded; charset=UTF-8 用于文件上传,我们必须明确将其更改为 false 以取消设置任何内容类型标头。

    PHP

    function upload_image()
    
    {
        if (isset($_FILES['file']['name'])) {
            $filename = $_FILES['file']['name'];
    
            $location = ;// Your desired location
            $imageFileType = pathinfo($location, PATHINFO_EXTENSION);
            $imageFileType = strtolower($imageFileType);
    
            $valid_extionsions = array("jpg", "jpeg", "png");
    
            $response = 0;
    
            if (in_array($imageFileType, $valid_extionsions)) {
                if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
                    $response = $location; // this is to return the file path after upload
                }
            }
            echo $response;
            exit;
        }
    }
    add_action("wp_ajax_upload_image", "upload_image");
    add_action("wp_ajax_nopriv_upload_image", "upload_image");
    

    请注意添加wp_ajaxwp_ajax_noprivwp_admin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2019-07-31
      • 2012-11-02
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多