admin管理员组

文章数量:1287631

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('/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?

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?

Share Improve this question asked Apr 4, 2018 at 16:49 Aleksandr EppAleksandr Epp 231 silver badge3 bronze badges 2
  • I'm inclined to agree that a for loop is the way to go, but don't quote me on that – Tom J Nowell Commented Apr 4, 2018 at 17:01
  • Hi you can use my plugin for it wordpress/plugins/upload-multiple-media-by-api – sandeep jain Commented Oct 13, 2021 at 8:56
Add a comment  | 

1 Answer 1

Reset to default 2

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.

本文标签: REST API multiple media upload