Last active
May 1, 2022 07:06
-
-
Save KevinBatdorf/f1cbe254a88af3287ba0790b229818dd to your computer and use it in GitHub Desktop.
Upload an image to the WordPress media library using the ImageData JavaScript object type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import apiFetch from '@wordpress/api-fetch' | |
// This is also set up to clone fields from an existing image. | |
// Just remove imageToClone and supply the missing fields on your own. | |
export const uploadImage = async (image: ImageData, imageToClone: WpImage): Promise<WpImage | undefined> => { | |
const canvas = document.createElement('canvas') | |
canvas.width = image.width | |
canvas.height = image.height | |
const ctx = canvas.getContext('2d') | |
if (!ctx) return | |
ctx.putImageData(image, 0, 0) | |
const blob: Blob = await new Promise((resolve) => { | |
canvas.toBlob((blob) => { | |
blob && resolve(blob) | |
}, imageToClone.mime_type) | |
}) | |
const formData = new FormData() | |
formData.append('file', new File([blob], imageToClone.media_details.file)) | |
formData.append('alt_text', imageToClone.alt_text) | |
formData.append('caption', imageToClone.caption.raw) | |
formData.append('description', imageToClone.description.raw) | |
return await apiFetch({ | |
path: 'wp/v2/media', | |
method: 'POST', | |
body: formData, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment