Upload file using Jquery and html in Wordpress

Hey Everyone,

I am trying to write an upload function for the frontpage on a WordPress website.
Firstly I started adding this to a view/template so it is loaded.

<form enctype="multipart/form-data" action="">
    <input type="file"   name="fileToUpload" id="fileToUpload">
</form>

In Jquery I’ve added this part

const upload = {
    init() {
        /**
         * FIXME : uitzoeken
         *
         */

        $('#fileToUpload').change((e) => {
            const ajaxUrl = window.wp_js.ajax_url;

            console.log($(e.currentTarget).parents('form')[0]);

            const formData = new FormData($(e.currentTarget).parents('form')[0]);

            const data = {
                action: 'ajaxUploadFile',
                formData,
            };

            $.ajax({
                url: ajaxUrl,
                method: 'POST',
                contentType: false,
                processData: false,
                cache: false,
                data,
                success: (returnData) => {
                    console.log(returnData);
                },
            });
        });
    },
};

export default upload;

The problem I am facing is that I cannot nest the formData in the data object or send it at all. So you see this:

How can I make sure I add the file (in binary). You need to add the action since Wordpress need to know how to handle the action.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.