• Hi

    I’m trying to upload an image to the Media library using the WP REST API but I keep getting a 400 (Bad Request) error at https://localhost/wp-json/wp/v2/media

    Here’s my HTML code:

    <form id="post-submission-form" enctype="multipart/form-data">
    	<input type="file" name="featured_media" id="featured_media"/>
    	<input type="submit" value="<?php esc_attr_e( 'Submit', 'your-text-domain' ); ?>">
    </form>

    And here’s my JavaScript:

    jQuery(document).ready(function ($) {
    
        $('#post-submission-form').on('submit', function (e) {
    
            e.preventDefault();
    
            var featured_media = $('#featured_media').val();
    
            var data = {
                source_url: featured_media
            };
    
            $.ajax({
                method: "POST",
                url: POST_SUBMITTER.root + 'wp/v2/media',
                data: data,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', POST_SUBMITTER.nonce);
                },
                success: function (response) {
                    console.log(response);
                },
                fail: function (response) {
                    console.log(response);
                }
            });
        });
    
    });

    Any ideas why I’m getting a 400 Bad Request error? The JavaScript is correct because when I change “wp/v2/media” to “wp/v2/posts” it works fine and creates a new post.

    Thanks
    Eric

    https://www.ads-software.com/plugins/json-rest-api/

Viewing 1 replies (of 1 total)
  • Thread Starter datafeedr

    (@datafeedrcom)

    This JavaScript seems to work. I’m not crazy about using FormData so there may be a better way:

    jQuery(document).ready(function ($) {
    
        $('#post-submission-form').on('submit', function (e) {
    
            e.preventDefault();
    
            var imageData = new FormData();
            imageData.append('file', $('input#featured_media')[0].files[0]);
    
            $.ajax({
                method: "POST",
                url: POST_SUBMITTER.root + 'wp/v2/media',
                data: imageData,
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', POST_SUBMITTER.nonce);
                },
                success: function (response) {
                    console.log(response);
                },
                fail: function (response) {
                    console.log(response);
                }
            });
        });
    });
Viewing 1 replies (of 1 total)
  • The topic ‘How to POST a new image to /wp/v2/media’ is closed to new replies.