WP REST API 以 Ajax 方式上传图片到 WordPress 后台

Upload images to WordPress backend via jQuery and WP REST API in Ajax.

While developing an application using the WordPress REST API, we need to upload images and files to the WordPress media library, and the official WordPress documentation does not describe a way to upload images. We develop aReact-based WordPress ThemesIn this theme, there is a form that needs to upload the post title, content, custom fields and images as the featured image of the post. In this theme, there is a form, in addition to the need to upload the title of the article, the content, but also need to upload custom fields and images as the featured image of the article.React to achieve this process is a relatively large amount of code, in order to simplify the description of the code, we use jQuery Ajax way to illustrate.

WP-API interface for uploading image files

WordPress REST API (WP-API) has a ‘/media’ endpoint, we just need to send the right data to this endpoint, and what format we need to send data to this endpoint to realize the image uploading, WordPress REST API does not mention it. The format of the data we need to send to this endpoint in order to upload images is not mentioned in the WordPress REST API, so we got stuck on this data format and spent a lot of time trying to get it to work.

Setting HTML5 Form Enctype Parameters

First we need to let the form know that we need to upload a file, by setting an enctype=”multipart/form-data” attribute to the form.

</form

Enctype parameter, the default is “text/plain”, if we need to upload images, we must set this parameter to “multipart/form-data”, otherwise in the first step, we can't realize the image upload.

Submitting Form Data with jQuery Ajax

Next, we need to use jQuery's Ajax method to submit data to the WordPress REST API, where we need to note that we need to add the X-WP-Nonce message to theImplementing WordPress REST API AuthenticationThe authentication method can be based on Cookie Authentication or Application Password Authentication.

Create a FormData() object to simulate a form.

FormData is a JavaScript object through which we can create a virtual form submission data and then send this data to the server to simulate the form submission operation. In the following operation, we create a FormData object named imageData, and then attach files to the imageData object. This object is the same as the form data we send to the server when we click the submit button to submit the form. It's just that we created it in code.

// Get the file object
var fileObject = $('input#file')[0].files[0] // or use the native method to get the file document.getElementById("photo").files[0];
var filename = fileObject.name;

// Create a dummy form and put the file into it
var imageData = new FormData(); // create a dummy form and put the file inside the form.
var imageData = new FormData(); imageData.append( "file", fileObject); // create a virtual form and put the file inside the form.;

Setting the proper HTTP header for proper data submission

Having completed the previous step, if we submit the file directly to the REST API, the API will still report an error because the API will assume by default that our submission is text. We also need to set a Content-Disposition HTTP header to let the API know that the data we are transferring is a file.

$.ajax({
    url: ajaxInfo.json_url + 'media?X-WP-Nonce' + ajaxInfo.nonce,
    type: 'POST', //Data: imageData, //ImageData.json_url + 'media?
    data: imageData, //This is the object created in the previous step.
    cache: false,
    contentType: false,
    processData: false,
    headers: { 'Content-Disposition': 'attachment;filename=test.jpg' },
    success: succes(res) // After the upload is successful, we can get the attachment ID and submit it along with the article as an attachment (featured_media) for the purpose of setting up a featured image for the article
});

In the above code, we set the file name of the upload to “test.jpg”, while in the actual project, we need to get the file name of the file that the user chooses to upload.

After successful upload, the REST API will return the object of the file we created successfully, and we can get the ID of the uploaded attachment, and then in the next processing, submit this ID as the featured image of the article (the parameter in the REST API interface is featured_media) to the article's API, and set the uploaded image as the featured image of the article. If we need to set something other than the featured image, we can also put the imageSet as a custom field for the article. In addition to developing WordPress themes, we can also develop a mobile APP or desktop application to allow users to upload and submit files through the REST API interface.

Related Posts

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *