1

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?

  • I'm inclined to agree that a for loop is the way to go, but don't quote me on that – Tom J Nowell Apr 4 '18 at 17:01
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.

  • Ok, that solution sounds ok to me, since I only need to upload a few pics (~5) at once. But just for the sake of clarity, you say "while not optimal" - what would be the optimal way? Given javascript client on the sender side and WordPress REST API on the receiver side? – Aleksandr Epp Apr 5 '18 at 9:41
  • As handling each request requires "booting" wordpress for each one of them, which is relatively expansive. Being able to send N images in one go would have saved some CPU resources, but it is against the nature of REST so if you didn't find such an API I will assume it does not exist. REST usually handles creation of one resource at a time. (I was forced to read what makes REST API different than others, will not bore you here, you can just read the relevant wiki articles as I have done ;) ) – Mark Kaplun Apr 5 '18 at 14:25
  • All right, thank you for clarification, now I got your point. – Aleksandr Epp Apr 6 '18 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.