我正在使用一个自定义端点来处理ajax媒体上载media_handle_upload()
.
我已经创建了一个自定义端点,该端点具有经过测试并可以工作的路由,但是当我尝试需要必要的文件以便使用时media_handle_upload()
, 它会在每次请求时返回500个内部服务器错误,但仍会将媒体正确上载到媒体库中。
我想弄明白这一点已经有一段时间了,但我不明白为什么会这样。
希望这里有人能给我指出正确的方向!
为了明确起见,一切都按预期进行,内部服务器错误不会妨碍上载的正确进行,但无论发生什么情况,每次请求都会发生错误。
Here is the function to upload: (path to custom routes file = /inc/custom-routes/custom-route.php)
function uploadFileFE ($data) {
if ( isset( $_FILES["file"] ) ) {
require ABSPATH . \'wp-admin/includes/image.php\';
require ABSPATH . \'wp-admin/includes/file.php\';
require ABSPATH . \'wp-admin/includes/media.php\';
$attachment_id = media_handle_upload( \'file\', 0 );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
echo $attachment_id->get_error_message();
} else {
// The image was uploaded successfully!
echo $attachment_id;
}
} else {
echo "The empty check failed! Something went horribly wrong!";
}
wp_die();
}
Update (with working code, adjusted from answer below)
因此,Sally CJ给出的答案是正确的,我正在用新代码进行更新,以便如果其他人犯了与我相同的错误,他们将看到完整的工作代码。
function uploadFileFE ($data) {
if ( isset( $_FILES["file"] ) ) {
//$glSiteUrl = get_site_url();
// These files need to be included as dependencies when on the front end.
require ABSPATH . \'wp-admin/includes/image.php\';
require ABSPATH . \'wp-admin/includes/file.php\';
require ABSPATH . \'wp-admin/includes/media.php\';
$attachment_id = media_handle_upload( \'file\', 0 );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
return $attachment_id->get_error_message();
} else {
// The image was uploaded successfully!
return $attachment_id;
}
} else {
return "The empty check failed! Something went horribly wrong!";
}
}
最合适的回答,由SO网友:Sally CJ 整理而成
从wp_die()
reference,
$args
(字符串|数组| int)(可选)控制行为的参数。如果$args
是整数,则将其视为响应代码。
\'response\' (int)HTTP响应代码。Ajax请求默认为200,否则为500。
因此REST API端点返回错误500
因为这是wp_die
作用
我建议您退回proper value —e、 通用航空公司WP_Error
实例出错,或WP_REST_Response
成功时的实例。尝试这些变化并比较响应:
Option 1
// Works, but with a 500 status code.
function uploadFileFE() {
wp_die();
}
Option 2
// Works, but shouldn\'t be used unless the client is *not* expecting a JSON response.
function uploadFileFE() {
echo \'foo\';
}
Option 3
// I\'d use this. WordPress will apply rest_ensure_response() to the returned value.
function uploadFileFE() {
return \'foo\';
//return WP_REST_Response( \'foo\' ); // or use this, or below to send an error..
//return new WP_Error( \'invalid_file\', \'Invalid file!\', array( \'status\' => 400 ) );
}