When developing applications using the WordPress REST API, we need to upload images and files to the WordPress media library, but the official WordPress documentation does not describe how to upload images. we develop aReact based WordPress themeWe encountered this problem when we were young. After researching for several hours, we found a way to upload pictures and share them here for the reference of friends who have the same needs. In this theme, there is a form that in addition to uploading the title and content of the article, you also need to upload custom fields and images as the featured image of the article. The amount of code to implement this process in React is relatively large. In order to simplify the explanation of the code, we use jQuery Ajax to illustrate.
WP-API interface used to upload image files
The WordPress REST API (WP-API) has an endpoint of ‘/media’. We only need to send appropriate data to this endpoint. What format of data needs to be sent to this endpoint to achieve image uploading is not mentioned in the WordPress REST API. We were stuck on this data format and spent a lot of time trying to succeed.
Set HTML5 form Enctype parameters
First we need to let the form know that we need to upload a file and set an enctype=”multipart/form-data” attribute to the form.
<form id="imageUpload" enctype="multipart/form-data">
<input type="file" id="file" />
<input type="submit" value="save file" />
</form>
The Enctype parameter defaults to “text/plain”. If we need to upload images, we must set this parameter to “multipart/form-data”, otherwise image upload will not be possible in the first step.
Submit form data using jQuery Ajax
Next, we need to use jQuery’s Ajax method to submit data to the WordPress REST API. What needs to be noted here is that we need to add the X-WP-Nonce information toImplement WordPress REST API authentication, we can use cookie-based authentication or application password authentication as the authentication method.
Create a FormData() object to simulate a form
FormData is a JavaScript object. We can use this object to create a virtual form to submit 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 the file to the imageData object. This object has the same meaning as the form data sent to the server when we click the submit button to submit the form. It’s just that we created this through code.
// 获取文件对象
var fileObject = $('input#file')[0].files[0] // 或者使用原生方法获取文件 document.getElementById("photo").files[0];
var filename = fileObject.name;
// 创建一个虚拟的表单,把文件放到这个表单里面
var imageData = new FormData();
imageData.append( "file", fileObject);
Set appropriate HTTP headers to submit data correctly
After completing the previous step, if we submit the file directly to the REST API, the API will still report an error because the API defaults to thinking that the content we submit is text. We also need to set up aContent-DispositionHTTP 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, //这个是上一步,创建的对象
cache: false,
contentType: false,
processData: false,
headers: { 'Content-Disposition': 'attachment;filename=test.jpg' },
success: succes(res) // 上传成功后,我们可以获取附件 ID,作为文章的附件(featured_media)和文章一起提交,来实现设置文章特色图像的目的
});
In the above code, we set the uploaded file name to “test.jpg”, but in the actual project, we need to get the file name that the user chooses to upload.
After the upload is successful, the REST API will return the object of the successfully created file. We can get the uploaded attachment ID, and then in the subsequent processing, submit this ID as the article’s featured image (the parameter in the REST API interface is featured_media) to the article’s API, and set the uploaded image as the article’s featured image. If what we need to set is not a 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 through the REST API interface to allow users to upload and submit files.
