Skip to content

Instantly share code, notes, and snippets.

@codersantosh
Created August 17, 2022 10:09
Show Gist options
  • Select an option

  • Save codersantosh/25eaf66de94ad07987bb67111ecbebfe to your computer and use it in GitHub Desktop.

Select an option

Save codersantosh/25eaf66de94ad07987bb67111ecbebfe to your computer and use it in GitHub Desktop.
Upload file from React/Gutenberg on WordPress
import apiFetch from "@wordpress/api-fetch";
export const fetchMedia = async (id) => {
let path = 'wp/v2/media/'+id,
media ={};
try {
media = await apiFetch({
path: path,
method : 'GET'
});
} catch (error) {
console.log('fetchMedia Errors:', error);
}
return media;
};
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import {
Button,
FormFileUpload
} from '@wordpress/components';
import { __unstableStripHTML as stripHTML } from '@wordpress/dom';
import {
uploadMedia
} from '@wordpress/media-utils';
import {
useEffect,
useState,
} from '@wordpress/element';
/*Lodash*/
const { isEmpty, isArray, uniq } = lodash;
/*Inbuilt APIs*/
import {
fetchMedia
} from "../../../../../api/media";
export function FileUpload({attachments = '', onChange}) {
let attachmentsArray = JSON.parse(attachments);
if( !isArray(attachmentsArray) ){
attachmentsArray = [];
}
const [filesInfo, setFilesInfo] = useState([]);
useEffect(() => {
async function init(){
if( !isEmpty(attachments)){
if( !isEmpty(attachmentsArray) && isArray(attachmentsArray)){
let filesInfoClone = [];
const promises = attachmentsArray.map(async function (itemId){
let mediaInfo = await fetchMedia(itemId);
filesInfoClone.push(mediaInfo);
})
await Promise.all(promises);
setFilesInfo(filesInfoClone);
}
}
}
init();
}, [attachments]);
let multiple = false,
allowedTypes = 'image/*';
const onUploadError = ( message ) => {
const safeMessage = stripHTML( message );
};
const onFilesUpload = ( files ) => {
uploadMedia({
allowedTypes: [ 'image' ],
filesList: files,
onFileChange: ( images ) => {
images.map(function (item){
if( !item || !item.id ){
return;
}
let attachmentsCloneArray = JSON.parse(attachments);
if( !isArray(attachmentsCloneArray) ){
attachmentsCloneArray = [];
}
attachmentsCloneArray.push(item.id);
onChange(JSON.stringify(uniq(attachmentsCloneArray)));
})
},
onError: onUploadError,
maxUploadFileSize:'',
wpAllowedMimeTypes:null
});
};
const onUpload = ( event ) => {
onFilesUpload( event.target.files );
};
const Preview = ({files}) => {
return files.map(function (item){
if( item.media_type === "image"){
return (
<a href={item.source_url} target="_blank">
<img
className="ed-form-image"
src={item.media_details && item.media_details.sizes && item.media_details.sizes.thumbnail && item.media_details.sizes.thumbnail.source_url?item.media_details.sizes.thumbnail.source_url:item.source_url}
alt={item.alt_text}
/>
</a>
)
}
})
}
return (
<FormFileUpload
onChange={ onUpload }
accept={ allowedTypes }
multiple={ multiple }
render={ ( { openFileDialog } ) => {
return (
<>
<Preview
files = {filesInfo}
/>
<Button
variant="primary"
onClick={ openFileDialog }
>
{ __( 'Upload' ) }
</Button>
</>
)
} }
/>
);
}
export default FileUpload;
@codersantosh
Copy link
Author

codersantosh commented Aug 17, 2022

attachments in FileUpload components: String(JSON encoded array )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment