Skip to content

Commit

Permalink
Fix issues with Openverse image names
Browse files Browse the repository at this point in the history
See #693
  • Loading branch information
swissspidy committed Sep 27, 2024
1 parent fc6b0c7 commit e419aa9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/upload-media/src/store/private-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { UploadError } from '../upload-error';
import {
canProcessWithFFmpeg,
cloneFile,
convertBlobToFile,
fetchFile,
getFileBasename,
getFileExtension,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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().
Expand Down
25 changes: 25 additions & 0 deletions packages/upload-media/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down

0 comments on commit e419aa9

Please sign in to comment.