REST API: upload media with advanced custom fields (ACF)

Question

Aim

I am trying to upload media via the REST API. I have successfully got it working, except for with the ACF data.

Problem

The media uploads successfully, but the acf fields are blank.

Code

    const route = `${API_URL}media`;
    const job = await getJobByCode(job_code); // {id: 127, acf: {job_code: 'ABC123'}, date: "2020-11-25T08:45:47", date_gmt: "2020-11-25T08:45:47", guid: {…}, modified: "2020-11-25T08:45:47", …}

    files.forEach(async (file) => {

        console.log(file); // File {uid: "rc-upload-1606293933971-10", name: "20201122_142537.jpg", lastModified: 1606015658320, lastModifiedDate: Sun Nov 22 2020 14:27:38 GMT+1100 (Australian Eastern Daylight Time), webkitRelativePath: "", …}

        const formData = new FormData();
        formData.append('file', file);
        formData.append('acf.job_object', job);
        // formData.append('fields.job_object', job);

        const res = await fetch(route, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${token}`,
            },
            body: formData,
        });

        const data = await res.json();

        console.log(data); // {id: 131, date: "2020-11-25T08:50:53", date_gmt: "2020-11-25T08:50:53", guid: {…}, modified: "2020-11-25T08:50:53", acf: [], …}

        if (data.errors) {
            console.error(data.errors);
            throw new Error('Error fetching API');
        }

        return data;
    });

0
Darcy 2 months 0 Answers 9 views 0

Leave an answer