如何在 wordpress 中通过 jQuery/Ajax 上传图片
Posted
技术标签:
【中文标题】如何在 wordpress 中通过 jQuery/Ajax 上传图片【英文标题】:How to upload image through jQuery/Ajax in wordpress 【发布时间】:2017-11-17 15:16:36 【问题描述】:我正在尝试从 wordpress 注册表单(自定义表单)上传图片。我找到了很多通过 ajax 上传的方法,但没有一个适合我。
这里是没有标签的表格
<div class="lofin-form"><div class="row">
<input type="text" name="first_name" id="first_name" placeholder="First Name" class="input" value="" size="20" />
</div>
<div class="row">
<lable>Id proof <input type="file" name="id_proof" id="id_proof" class="input" />
</div>
<p class="submit"><input type="submit" name="wp-submit" id="wp-submit-register" class="btn vernil small" value="'.__('Sign Up','wpestate').'" /></p>
</div>
这里是 jQuery 脚本代码
$('#wp-submit-register').click(function()
wpestate_register();
);
function wpestate_register ()
var user_role = $('#first_name').val();
var fdata = new FormData();
fdata.append('file', $('#id_proof')[0].files[0]);
$.ajax(
type: 'POST',
url: ajaxurl,
data:
'action' : 'ajax_free_register_form',
'first_name' : first_name,
'file_data' : fdata
,
success:function(data)
alert('success');
这里是php函数
add_action( 'wp_ajax_nopriv_ajax_free_register_form', 'ajax_free_register_form' );
add_action( 'wp_ajax_ajax_free_register_form', 'ajax_free_register_form' );
function ajax_free_register_form()
$first_name = trim( $_POST['first_name'] ) ;
$id_proof = $_FILES['id_proof'] ;
解决[编辑]
只需在表单中添加表单标签并提供 ID 'user_reg_form'。
<form id="user_reg_form" action="" method="post" enctype="multipart/form-data">
----------------------input fields goes here-------------------
</form>
并更新脚本:
$('#wp-submit-register').click(function()
wpestate_register();
);
function wpestate_register ()
var formdata = new FormData( $("#user_reg_form")[0] );
formdata.append('action', 'ajax_free_register_form');
$.ajax(
type: 'POST',
cache: false,
contentType: false,
processData: false,
url: ajaxurl,
data: formdata,
success:function(data)
alert('success');
);
之后,您可以简单地获取上传的文件
$attachment = $_FILES['id_proof'];
【问题讨论】:
【参考方案1】:确保您的 ajax 版本支持它。并且您需要将 ajax processData 和 contentType 设置为 FALSE。 Para contentType 表示不设置 Content-Type HEAD,processData 表示不将数据处理成字符串。
试试这个:
$.ajax(
type: 'POST',
url: ajaxurl,
data: fdata,
processData : false,
contentType: false,
success:function(data)
alert('success');
【讨论】:
我做到了,但没有运气:(【参考方案2】:在wordpress中通过jQuery/Ajax上传图片
html:
<input type="file" id="ct-file" name="ct_file">
JS:
var sofg_mixup = jQuery.noConflict();
sofg_mixup(document).ready(function()
sofg_mixup('#ct-file').change(function()
var fileInput = sofg_mixup('#ct-file').prop('files')[0];
var myFormData = new FormData();
myFormData.append('ct_file', fileInput);
sofg_mixup.ajax(
url: '<?php echo get_template_directory_uri() ?>/save_file.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType: 'json',
data: myFormData,
success: function(jsonData)
console.log(jsonData.url);
,
error: function(xhr, ajaxOptions, thrownError)
console.log(xhr);
);
);
);
PHP
require_once('../../../../../wp-load.php');
if (isset($_FILES['ct_file'] ) && !empty($_FILES['ct_file']['name']) )
$allowedExts = array("doc", "docx", "pdf");
$temp = explode(".", $_FILES["ct_file"]["name"]);
$extension = end($temp);
if ( in_array($extension, $allowedExts))
if ( ($_FILES["ct_file"]["error"] > 0) && ($_FILES['ct_file']['size'] <= 3145728 ))
$response = array(
"status" => 'error',
"message" => 'ERROR Return Code: '. $_FILES["ct_file"]["error"],
);
else
$uploadedfile = $_FILES['ct_file'];
$upload_name = $_FILES['ct_file']['name'];
$uploads = wp_upload_dir();
$filepath = $uploads['path']."/$upload_name";
if ( ! function_exists( 'wp_handle_upload' ) )
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) )
$file = $movefile['file'];
$url = $movefile['url'];
$type = $movefile['type'];
$attachment = array(
'post_mime_type' => $type ,
'post_title' => $upload_name,
'post_content' => 'File '.$upload_name,
'post_status' => 'inherit'
);
$attach_id=wp_insert_attachment( $attachment, $file, 0);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
$response = array(
"status" => 'success',
"url" => $url
);
else
$response = array(
"status" => 'error',
"message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
);
print json_encode($response);
exit;
【讨论】:
我正在使用带有“Action”的 ajax。你能告诉我在哪里添加“动作”吗? 对文件的操作:save_file.php :) 如果你会看到我正在使用 wordpress ajax 功能 向数据添加操作:myFormData.append("action", "ajax_free_register_form")。函数 ajax_free_register_form() 将包含 php 代码【参考方案3】:使用 ajaxForm() jquery 插件。它会像魅力一样为您服务。参考http://malsup.com/jquery/form/#getting-started
也请参考https://forum.jquery.com/topic/using-ajaxsubmit-function-extra-parameter
【讨论】:
以上是关于如何在 wordpress 中通过 jQuery/Ajax 上传图片的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Rails 中通过 jQuery 调用 JSON 文件?
SSL 证书在 WordPress 更新中通过纯 HTTP(非 SSL)验证失败