import React from 'react' import { Typography } from '@material-ui/core' import IconButton from '@material-ui/core/IconButton' import PhotoCamera from '@material-ui/icons/PhotoCamera' import { toast } from 'react-toastify' import { apiUploadFile } from 'app/apis/Functions/Upload.js' import { CKEditor } from '@ckeditor/ckeditor5-react' const supportedExtensions = ['jpeg', 'jpg', 'png'] const validateImg = (string) => { const path = string.name.split('.') const extension = `${path[path.length - 1]}` if (supportedExtensions.includes(extension)) { return true // TODO: upload } else { // TODO: show "invalid file type" message to user // reset value return false } } function UploadButtons(props) { const { images, onFileChange, title } = props const upLoadImage = async (event) => { if (validateImg(event.target.files[0])) { const res = await apiUploadFile( createFormData(event.target.files[0], {}) ) console.log('res image', res) if (res.data.status == 200 && res.data.data) { console.log(res.data.data[0].url) onFileChange(res.data.data[0].url) toast.success('Upload ảnh thành công!', { theme: 'colored', }) } else { toast.success('Upload ảnh thất bại!', { theme: 'colored', }) } } else { toast.warn('File không đúng định dạng!', { theme: 'colored', }) } } const createFormData = (photo, body) => { const data = new FormData() Object.keys(body).forEach((key) => { data.append(key, body[key]) }) if (photo) { data.append('files', photo) } return data } return ( <div> <Typography color="textSecondary">{title}</Typography> <input accept="image/*" style={{ display: 'none' }} id="contained-button-file" onChange={upLoadImage} type="file" /> <label htmlFor="contained-button-file"> {images ? ( <img src={images} style={{ width: 100, height: 100, borderRadius: 5, cursor: 'pointer', }} /> ) : ( <IconButton style={{ width: 100, height: 100, borderRadius: 5, border: '1px dashed gray ', }} color="primary" component="span" > <PhotoCamera /> </IconButton> )} </label> </div> ) } export default UploadButtons