From e419aa9e12f1d34e1347122ca7a76cfca39554f9 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Fri, 27 Sep 2024 11:00:31 +0200 Subject: [PATCH] Fix issues with Openverse image names See #693 --- .../upload-media/src/store/private-actions.ts | 10 ++++++-- packages/upload-media/src/utils.ts | 25 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 7ed5ee96..76bede6c 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -21,6 +21,7 @@ import { UploadError } from '../upload-error'; import { canProcessWithFFmpeg, cloneFile, + convertBlobToFile, fetchFile, getFileBasename, getFileExtension, @@ -153,7 +154,8 @@ type ThunkArgs = { }; interface AddItemArgs { - file: File; + // It should always be a File, but some consumers might still pass Blobs only. + file: File | Blob; batchId?: BatchId; onChange?: OnChangeHandler; onSuccess?: OnSuccessHandler; @@ -183,7 +185,7 @@ interface AddItemArgs { * @param [$0.operations] List of operations to perform. Defaults to automatically determined list, based on the file. */ export function addItem( { - file, + file: fileOrBlob, batchId, onChange, onSuccess, @@ -202,6 +204,10 @@ export function addItem( { const itemId = uuidv4(); + // Hardening in case a Blob is passed instead of a File. + // See https://github.com/WordPress/gutenberg/pull/65693 for an example. + const file = convertBlobToFile( fileOrBlob ); + let blobUrl; // StubFile could be coming from addItemFromUrl(). diff --git a/packages/upload-media/src/utils.ts b/packages/upload-media/src/utils.ts index b674c95e..a9a8dd36 100644 --- a/packages/upload-media/src/utils.ts +++ b/packages/upload-media/src/utils.ts @@ -18,6 +18,31 @@ import { } from './constants'; import { UploadError } from './upload-error'; +/** + * Converts a Blob to a File with a default name like "image.png". + * + * If it is already a File object, it is returned unchanged. + * + * @param fileOrBlob Blob object. + * @return File object. + */ +export function convertBlobToFile( fileOrBlob: Blob | File ): File { + if ( fileOrBlob instanceof File ) { + return fileOrBlob; + } + + // Extension is only an approximation. + // The server will override it if incorrect. + const ext = fileOrBlob.type.split( '/' )[ 1 ]; + const mediaType = + 'application/pdf' == fileOrBlob.type + ? 'document' + : fileOrBlob.type.split( '/' )[ 0 ]; + return new File( [ fileOrBlob ], `${ mediaType }.${ ext }`, { + type: fileOrBlob.type, + } ); +} + /** * Renames a given file and returns a new file. *