在Wordpress插件中通过Ajax和jquery上传选择文件的文件 [英] Upload a file on choosing file through ajax and jquery in wordpress plugin

查看:87
本文介绍了在Wordpress插件中通过Ajax和jquery上传选择文件的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在wordpress管理插件中具有邮件功能,我希望能够动态附加文件并通过邮件作为附件发送.我使用ajax方法,但我不知道如何通过ajax发送输入文件 这是html代码

i have a mail feature in wordpress admin plugin and i want the ability to attach a file dynamically and send it through mail as an attachment. i using ajax method but i did not know how to send input file through ajax This is html code

<div class="kids-top-right-view">
  <ul class="kids-list kids-list-inline kids-nav-item">
        <li>
          <a>
              <i class="fa fa-envelope-o"></i> Email</a>
      </li>

    </ul>
    <div class="note_container">
      <form method="post" id="mail_parent_form" enctype="multipart/form-data">
        <input type="hidden" name="action" value="attach_file_parent">
        <p class="email-from">
            <label>From</label>
            <span class="sep">:</span>
            <span class="value">Casting Kids(office@castingkids.com.au)</span>
        </p>
        <p class="email-to">
            <label>To</label>
            <span class="sep">:</span>
            <span class="value"><?=$child[0]->fname.' '.$child[0]->lname?></span>
            <input type="hidden" class="email_address" value="<?=$child[0]->email?>">
        </p>
        <p class="email-subject">
            <label>Subject</label>
            <span class="sep">:</span>
            <span class="value">
                <input type="text" name="email_subject" placeholder="Subject...">
            </span>
        </p>
        <div id="parent_mail">
          <trix-editor placeholder="Type your email body ....."></trix-editor>

          <div class="client-action">
      <input type="submit" class="button button-primary" id="email_P" name="email_parent" value="Send Mail" >
      <input type="file" name="file[]" id="email_file" multiple>
      <label for="email_file">Attach File</label>
      <input type="reset" class="button button-default" value="Discard">
      <p style="display: none;" class="error_message"></p>
      <p style="display: none;" class="success_message"></p>
  </div>
        </div>
    </form>
  </div>
</div>

jQuery代码

$("#email_file").on('change',function(){
  var input = document.getElementById('email_file');
  var files = input.files;
  data = {'action':'attach_file_parent','files':files};
  jQuery.post(ajaxurl, data, function(response) {

  })
})

但是它给了我这个错误:非法调用 因为我不知道在哪里添加这一行processData:false来解决此错误,我必须对ajax使用此方法.我不能使用这个

But it gives me this error: Illegal Invocation beacause i dont know where to add this line processData: false to tackle this error and i have to use this method for ajax. i cant be able to use this

$.ajax({
    url  : ajaxurl,
    type : 'POST',
    data : formData,
    contentType: false,
    processData: false
}) 

因为它给了我ajax找不到错误 请为此向我提出建议,谢谢

as it gives me ajax not found error Please suggest me with this, thank you

推荐答案

请检查下面的代码以通过 Ajax

Please check the code below to upload form image through Ajax

JS代码

var form  = new FormData();
var image = jQuery('#img_avatar')[0].files[0]; //We have only one file and this is how we get it.

        //Now we add all the data to the form instance in a key value pair. 
        //Notice that we called it image here. if you change it then change it in the
        //media_handle_upload('image', 0); function as well. 
        form.append('image', image);
        form.append('current_user_id', current_user_id);
        form.append('action', 'cvf_upload_files');  
        //Using localize script to pass "site_url" and "nonce"
        jQuery.ajax({
            url: ajax_url,
            type: 'POST',
            data: form,
            contentType: false,
            processData: false
        }).done(function(data){
            // console.log("data is: ", data);
        }).fail(function(data){
            // console.log("errors are: ", error);
        });

您需要添加ID为 img_avatar

WordPress代码(PHP)

add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files');
add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission

function cvf_upload_files(){

$parent_post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0;  // The parent ID of our attachments
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg"); // Supported file types
$max_file_size = 1024 * 500; // in kb
$max_image_upload = 10; // Define how many images can be uploaded to the current post
$wp_upload_dir = wp_upload_dir();
$path = $wp_upload_dir['path'] . '/';
$count = 0;
$photoattach_id = '';

$attachments = get_posts( array(
    'post_type'         => 'attachment',
    'posts_per_page'    => -1,
    'post_parent'       => $parent_post_id,
    'exclude'           => get_post_thumbnail_id() // Exclude post thumbnail to the attachment count
) );

// Image upload handler
if( $_SERVER['REQUEST_METHOD'] == "POST" ){

    // Check if user is trying to upload more than the allowed number of images for the current post

        $upload_img = $_FILES['image'];

        if($upload_img['size']!=0){
            $photoattach_id = '';
            $uploadedfile = $upload_img;
            $upload_overrides = array( 'test_form' => FALSE );
            $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
            if ( $movefile ) {
            } else {
            //echo "Possible file upload attack!\n";
            } 
            if ( $movefile) {

                $wp_filetype = $movefile['type'];
                $filename = $movefile['file'];
                $wp_upload_dir = wp_upload_dir();
                $attachment = array(
                    'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
                    'post_mime_type' => $wp_filetype,
                    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                if($uploadedfile['error']== 0){
                    $photoattach_id = wp_insert_attachment( $attachment, $filename);
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    $attach_data = wp_generate_attachment_metadata( $photoattach_id, $filename );
                    $res1= wp_update_attachment_metadata( $photoattach_id, $attach_data );
                }
            }

        }

        if(!empty($photoattach_id)){
             $current_user_id = $_POST['current_user_id'];

            if(get_user_meta($current_user_id, 'user_avatar', FALSE)) { 
                update_user_meta($current_user_id, 'user_avatar', $photoattach_id);
            } else { // If the custom field doesn't have a value
                add_user_meta($current_user_id, 'user_avatar', $photoattach_id);
            }

        }
}

exit();
}

这篇关于在Wordpress插件中通过Ajax和jquery上传选择文件的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆