最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - How to require files in a custom endpoint

programmeradmin1浏览0评论

I am working on a custom endpoint to handle ajax media uploads with media_handle_upload().

I have created a custom endpoint with a route that is tested and works, however when I try require the necessary files so that I can use media_handle_upload(), it returns a 500 internal server error with each request but still uploads the media correctly in to the media library.

I have tried to figure this out for a while now but I dont understand why it's happening.

Hoping somebody here can point me in the right direction!

To clearify, everything works as expected, the internal server error does not hinder the upload to happen correctly, but the error occurs with every request, no matter what.

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)

So, the answer that Sally CJ gave was correct, I'm updating with the new code so that if anyone else does the same mistake I did, they'll see the complete working code.

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!";
          }

        }

I am working on a custom endpoint to handle ajax media uploads with media_handle_upload().

I have created a custom endpoint with a route that is tested and works, however when I try require the necessary files so that I can use media_handle_upload(), it returns a 500 internal server error with each request but still uploads the media correctly in to the media library.

I have tried to figure this out for a while now but I dont understand why it's happening.

Hoping somebody here can point me in the right direction!

To clearify, everything works as expected, the internal server error does not hinder the upload to happen correctly, but the error occurs with every request, no matter what.

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)

So, the answer that Sally CJ gave was correct, I'm updating with the new code so that if anyone else does the same mistake I did, they'll see the complete working code.

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!";
          }

        }
Share Improve this question edited Apr 26, 2019 at 12:34 Steve Rodgers asked Apr 26, 2019 at 1:21 Steve RodgersSteve Rodgers 156 bronze badges 6
  • What's your register_rest_route() code? Is the uploadFileFE the endpoint callback? But even if not, you shouldn't call wp_die() or do echo there. – Sally CJ Commented Apr 26, 2019 at 3:30
  • The route works fine. Yes, uploadFileFE is the callback. It's only when i require the files you see required in the function that things get messy. And I don't understand why. If i remove the require files, I get no error other than the undefined function of wp_handle_upload ofc, since it's dependencies is lacking without those files. – Steve Rodgers Commented Apr 26, 2019 at 3:40
  • 1 My answer might help? And in your code, you might want to use require_once instead of require... just in case. – Sally CJ Commented Apr 26, 2019 at 4:50
  • Does the code definitely not work if you don't include the files? Have you confirmed that they need to be included? – Jacob Peattie Commented Apr 26, 2019 at 7:51
  • @JacobPeattie The code does not work if the files are not included, no. – Steve Rodgers Commented Apr 26, 2019 at 12:24
 |  Show 1 more comment

1 Answer 1

Reset to default 0

From the wp_die() reference,

$args
(string|array|int) (Optional) Arguments to control behavior. If $args is an integer, then it is treated as the response code.

'response' (int) The HTTP response code. Default 200 for Ajax requests, 500 otherwise.

So your REST API endpoint returns the error 500 because that's the default header status sent by the wp_die function.

And I recommend you to return a proper value — e.g. a WP_Error instance on error, or a WP_REST_Response instance on success. Try these variations and compare the responses:

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 ) );
}
发布评论

评论列表(0)

  1. 暂无评论