After I figured out how to upload an image using the /media endpoint, I was wondering, how multiple images could be uploaded at the same time. For now I’m using following code:

const globFiles = []; // an array of files retrieved from file input
const onClick = () => {
return fetch('http://my.host/wp-json/wp/v2/media', {
    method: 'POST',
    headers: {
        'Content-Type': 'image/jpeg',
        'X-WP-Nonce': window.nonce,
        'Content-Disposition': `attachment; filename="${globFiles[0].name}"`
    },
    body: globFiles[0]
}).then(response => response.json())
    .then((json) => {
        console.log(json) // here I receive the media object
    }).catch((error) => {
        console.error(error);
    });
}

Is media endpoint capable of handling an array of files? The problem in my current code would be the content-disposition header, as I provide the file name there. So is wrapping it in a for-loop the way to go?

1 Answer
1

While not optimal, there is nothing stopping you from sending two requests at the same time and to continue your logic after both responses are received. This is relatively easy with jQuery or JS promises, but most likely possible in all languages which has an API to send HTTP requests asynchronously.

Just keep in mind that handling the requests are expensive in CPU resources, so be careful and don’t try to send 1000 images at once.

Tags:

Leave a Reply

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