WordPress Upload Files with Ajax
How do you upload files to WordPress with Ajax? Maybe you want fileupload functionality on the front end or enable file uploads in your WordPress plugin. There are a lot of good tutorials on this subject but I couldn’t find any simple example that works with native WP files.
If you check out how WordPress manages media, you will see that a file upload is just a POST call to /wp-admin/async-upload.php. It is an Ajax call that passes form data to that file and formdata consists of 4 attributes:
- name – the name of the file
- action – upload-attachment
- _wpnonce – special token needed for security
- async-upload – the actual file
If you have a regular file input field on the page, you can easily query for the uploaded file and filename from the DOM element. You can retrieve the proper nounce token with php when the page loads via wp_create_nonce(‘media-form’) where media-form is the action for the nounce. This token code happens to be already available in a script tag that gets injected into the bottom of the page with wp_plupload_default_settings. If you see it on your page, you can grab it via _wpPluploadSettings.defaults.multipart_params._wpnonce. Finally, the action is upload-attachment.
This works for me in a plugin admin page and the response is a JSON object with success flag, file url, all kinds of meta data about the file, and nonces for next actions like deleting the file from the media library.
Introduction to WordPress Nonces
Upload Files in WordPress