file upload using camera and fileupload
import React, { useEffect, useState } from 'react'
import { ToastContainer, toast } from '../../../node_modules/react-toastify';
import '../../../node_modules/react-toastify/dist/ReactToastify.css';
import Swal from '../../../node_modules/sweetalert2';
import { useRef, useCallback } from 'react';
import Webcam from '../../../node_modules/react-webcam';
import './style/WebcamComponent.css';
// Create a CSS file for styling
import { FiArrowLeft } from "react-icons/fi";
import topImg from '../../Assets/babybump/Group.png';
// import topImg from '../assets/Group.png';
// import leftImg from '../assets/Vector 1762.png';
import leftImg from '../../Assets/babybump/Vector 1762.png';
// import phoneImg from '../assets/Group 39286.png';
import phoneImg from '../../Assets/babybump/Group 39286.png';
// import trashImg from '../assets/trash.png'
import trashImg from '../../Assets/babybump/trash.png';
// import baby from '../assets/Baby.png'
import baby from '../../Assets/babybump/Baby.png';
// import Mother from '../assets/Mother.png';
import Mother from '../../Assets/babybump/Mother.png';
// import Calender from '../assets/Calender.png'
import Calender from '../../Assets/babybump/Calender.png';
// import Camera from '../assets/camera.png'
import Camera from '../../Assets/babybump/camera.png';
// import Gallery from '../assets/Gallery.png'
import Gallery from '../../Assets/babybump/Gallery.png';
import Accordion from '@mui/material/Accordion';
import { CiCamera } from "react-icons/ci";
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
// import { useNavigate,useParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import jsonData from "./Data.json";
import Box from '@mui/material/Box';
import useFetch from './useFetch';
import Typography from '@mui/material/Typography';
import Modal from '@mui/material/Modal';
import Variables from '../../Global.ts'
import axios from 'axios';
import CircularProgress from '@mui/material/CircularProgress';
import CameraPhoto from 'react-html5-camera-photo';
import 'react-html5-camera-photo/build/css/index.css';
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '80vw',
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
pt: 2,
px: 4,
pb: 3,
};
export default function Detail(props) {
// const [data]=useFetch();
// console.log('',data);
const [open, setOpen] = React.useState(false);
const { id} = useParams();
const [photo,setphoto]=useState('');
const [loading,setLoading]=useState(false);
// const imagepath= data.filter(e=>e.month===id);
// console.log(imagepath);
// const mydata=imagepath[0];
// console.log(typeof(mydata));
// if(mydata){
// console.log(mydata.photo);
// if(mydata.photo){
// // console.log(mydata.photo);
// }
// }
const [data,setData]=useState([]);
const [camera1,setcamera1]=useState(false);
const babyBumpTrackerDetails = async () => {
console.log( localStorage.getItem('token'));
try {
let response = await fetch(Variables.get_Base_Url()+'/api/hospital-app/get_baby_bump_tracker/images/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Token ' + localStorage.getItem('token'),
},
body: JSON.stringify({"patient_slug":localStorage.getItem('patient_slug')})
});
let json = await response.json();
console.log(json.images_data);
setLoading(false);
if(json.SUCCESS){
setLoading(true);
setData(json.images_data);
const imagepath= json.images_data.filter(e=>e.month===id);
console.log(imagepath);
const mydata=imagepath[0];
console.log(mydata);
setphoto(mydata.photo)
console.log(mydata.photo);
}
} catch (error) {
console.error(error);
}
};
const fileInput=useRef(null);
// console.log(id);
const handleClose = () => setOpen(false);
const [babyData,setbabyData]=useState();
const [MomData,setMomData]=useState();
const [PregnancyListData,setPregnancyListData]=useState();
// const navigate = useNavigate();
const [camera,setcamera]=useState(false);
const [picture,setPicture]=useState([]);
const [showoption,setshowoption]=useState();
const [selectedFile, setSelectedFile] = useState(null);
const filterData= async()=>{
console.log("my details page",jsonData);
let output =
jsonData.filter(data => data.month == id);
for (let i = 0; i < output.length; i++) {
console.log(output[i])
setbabyData(output[i].data.Baby)
setMomData(output[i].data.Mom)
setPregnancyListData(output[i].data.PregnancyQuickList)
// console.log("hellosir",output[i].data.PregnancyQuickList);
};
}
useEffect(()=>{
babyBumpTrackerDetails();
// console.log("details page",jsonData);
filterData();
},[])
const uploadbabybumpTracker=async()=>{
await console.log('api called');
props.history.push('/femme-app/Baby');
// navigate('/babybumptracker/home');
}
const backbuttonHandler=()=>{
// console.log('back button clicked');
// navigate('/babybumptracker/home');
if(picture.length===1){
uploadbabybumpTracker();
}
else{
console.log('image upload api not call');
props.history.push('/femme-app/Baby');
// navigate('/babybumptracker/home');
}
}
const handleCameraClick=()=>{
setOpen(true)
}
/*take a picture*/
const webcamRef = useRef(null);
const videoConstraints = {
width: 1280,
height: 720,
facingMode: 'environment',
};
const takePictureHandler = useCallback(() => {
setPicture([]);
setOpen(false)
setcamera(true);
setTimeout(() => {
setshowoption('show')
}, 1000);
// const imageSrc = webcamRef.current.getScreenshot();
// console.log(imageSrc);
// You can use the captured image data as needed
}, []);
/*end of take a picture*/
const capture=()=>{
const imageSrc = webcamRef.current.getScreenshot();
console.log('1st Captured image:', imageSrc);
///.......//
// console.log('api of upload has to be called....');
camerclickupload(imageSrc);
// setPicture([imageSrc]);
setcamera(false);
}
const camerclickupload = async(file1) => {
console.log('uploaded');
console.log(file1);
// console.log({id}.id.charAt(0));
const currentmonth=({id}.id.charAt(0))
// Convert the base64 string to a File object
// Extract the base64 data (remove the data URI prefix)
const base64Data = file1.split(',')[1];
// Convert base64 string to Blob
const blob = base64toBlob(base64Data, 'image/jpeg');
console.log(blob);
console.log('........');
// Prepare FormData
const formData = new FormData();
formData.append('file', blob);
formData.append('month',currentmonth);
formData.append('patient_slug',localStorage.getItem('patient_slug'));
formData.append('upload_type','baby_bump_tracker')
console.log(formData);
axios.post(Variables.get_Base_Url()+'/api/hospital-app/upload_baby_bump_tracker/',formData,{
headers: {
Authorization: 'Token ' + localStorage.getItem('token'),
},
}).then(res=>{
console.log(res);
setPicture([file1]);
toast.warn(`${id} month image uploaded successfully`,{draggable:false});
}).catch(Error=>console.log(Error))
}
const base64toBlob = (base64Data, contentType) => {
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: contentType });
};
const clearHandler=()=>{
setcamera(false);
}
const deleteCameraClick=()=>{
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
deleteHandler();
setPicture([]);
setcamera(false);
}
});
// setPicture([]);
// setcamera(false);
}
const deleteHandler=async()=>{
console.log('delete handler called...');
const currentmonth=({id}.id.charAt(0))
try {
let response = await fetch(Variables.get_Base_Url()+'/api/hospital-app/delete_baby_bump_tracker_uploaded_image/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Token ' + localStorage.getItem('token'),
},
body: JSON.stringify({"patient_slug":localStorage.getItem('patient_slug'),"month":currentmonth})
});
let json = await response.json();
console.log(json)
if(json.SUCCESS){
babyBumpTrackerDetails();
Swal.fire({
title: "Deleted!",
text: "Your file has been deleted.",
icon: "success"
});
}
} catch (error) {
console.error(error);
}
}
const handleFileChange = (e) => {
const file = e.target.files[0];
console.log(file);
setSelectedFile(file);
handleUpload(file);
// const imageUrl = URL.createObjectURL(file);
// setPicture(imageUrl);
setOpen(false);
};
const handleUpload = async(file) => {
console.log('uploaded');
// Your file upload logic here
// if (selectedFile) {
console.log(file);
const imageUrl = URL.createObjectURL(file);
setPicture(imageUrl);
// console.log({id}.id.charAt(0));
const currentmonth=({id}.id.charAt(0))
const formData = new FormData();
formData.append('file', file);
// body: {"month":7,"patient_slug":localStorage.getItem('patient_slug'),
// 'upload_type':'baby_bump_tracker'}
formData.append('month',currentmonth);
formData.append('patient_slug',localStorage.getItem('patient_slug'));
formData.append('upload_type','baby_bump_tracker')
console.log(formData);
axios.post(Variables.get_Base_Url()+'/api/hospital-app/upload_baby_bump_tracker/',formData,{
headers: {
Authorization: 'Token ' + localStorage.getItem('token'),
},
}).then(res=>{
console.log(res);
setPicture(imageUrl);
toast.warn(`${id} month image uploaded successfully`,{draggable:false});
}).catch(Error=>console.log(Error))
}
/*const openCamera = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.capture = 'environment'; // Opens rear camera. Use 'user' to open front camera.
input.onchange = (event) => {
const file = event.target.files[0];
// Do something with the captured image
};
input.click();
};*/
const handleTakePhoto = (dataUri) => {
// Do something with the captured photo data (dataUri)
setcamera1(false);
console.log('Photo captured!', dataUri);
};
const handleCameraError = (error) => {
// Handle camera errors
console.error('Camera error:', error);
};
// const takepichandler=()=>{
// setOpen(false)
// setcamera1(true);
// }
return (
<div style={{margin:'2vw'}}>
<div style={{ display: 'flex', padding: 20, alignItems: 'flex-end', }}>
<div style={{ width: '20vw' }} >
<FiArrowLeft style={{ height: 25, width: 25, marginRight: 5, }} onClick={ backbuttonHandler}></FiArrowLeft>
</div>
<div style={{ width: '60vw', textAlign: 'center', lineHeight: 1.8 }} ><span className='blogtext'>{camera?'Select Preview':`${id}`}
{id==2?'nd':''}
{id==1?'st':''}
{id==3?'rd':''}
{id>3&&'th'}
Month
</span></div>
</div>
{/* {picture.length} */}
{loading===false?
<Box sx={{ display: 'flex' }}>
<CircularProgress />
</Box>
:
<>
{
photo?
<>
<img src={photo} height='255px' width='100%'/>
{/* <img src="https://newstaging.vidalhealth.com:7743/media/health_tools_media/bbt/lKXV9MkD1C/Capture.PNG" height='255px' width='100%'/> */}
<div className="bottom-left1" style={{background:'#000000',borderRadius:'100%', width:'30px',height:'30px',paddingLeft:'5.0px',paddingTop:'5.0px',}}>
<img src={trashImg} style={{ height:20,width:'20'}} onClick={deleteCameraClick} />
</div>
</>
:
<>
{picture.length!=0&&
<>
<img src={picture} style={{ height:255,width:'96vw'}} />
<div className="bottom-left1" style={{background:'#000000',borderRadius:'100%', width:'30px',height:'30px',paddingLeft:'5.0px',paddingTop:'4.0px',}}>
<img src={trashImg} style={{ height:20,width:'20'}} onClick={deleteCameraClick} />
</div>
<div className="bottom-left2" style={{background:'#000000',borderRadius:'100%', width:'30px',height:'30px',paddingLeft:'5.0px',paddingTop:'5.0px',}} onClick={handleCameraClick}>
<CiCamera style={{color:'white'}}/>
</div>
</>
}
{/* {!camera} */}
{/* {picture.length} */}
{!camera&&picture.length==0&&<>
<div style={{ display: 'flex',width:'96vw',background:'#007071'}}>
<div style={{weight:'30vw'}}>
<img src={topImg} style={{ height:255,width:'50vw'}} />
</div>
<div style={{weight:'30vw', marginLeft:'-1.5vw'}}>
<img src={leftImg} style={{ height:180,width:'10vw'}} />
</div>
<div style={{weight:'30vw'}}>
<img src={phoneImg} style={{ height:180,width:'10vw'}} />
<p style={{textAlign:'left',fontSize:'1.1em',wordWrap: 'break-word',color:'#ffffff'}}>
Stand straight and take a picture of your baby bump from a side angle in portrait view.
</p>
<div style={{background:'#000000',borderRadius:'100%', width:'30px',height:'30px',paddingLeft:'6.0px',paddingTop:'2.0px',marginLeft:'24vw'}} onClick={handleCameraClick}>
<CiCamera style={{color:'white'}}/>
</div>
</div>
</div>
</>}
</>
}
</>
}
{ /*camer click*/ }
{camera?<div>
<div className="webcam-container">
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/jpeg"
videoConstraints={videoConstraints}
style={{ width: '100%', height: '90vh' }}
/>
{/* <div className="crop-overlay" /> */}
</div>
{/* {showoption} */}
{showoption&&<div style={{}}>
<div style={{display:'flex',background:'',width:'100%',justifyContent:'space-between',background:'black',marginTop:-4,height:'20px'}}>
<div style={{color:'#ffffff'}} onClick={()=>clearHandler()}>cancel</div><div style={{color:'#ffffff'}} onClick={()=>capture()}>done</div>
</div>
</div>}
</div>
:
<>
<div style={{width:'96vw'}}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1-content"
id="panel1-header"
>
<img src={baby} style={{ height:'8vh',width:'8vw'}} /> <span style={{paddingTop:'2.5vh',fontWeight:500,fontSize:'1.3em'}}>Baby</span>
</AccordionSummary>
<AccordionDetails>
{babyData}
</AccordionDetails>
</Accordion>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel2-content"
id="panel2-header"
>
<img src={Mother} style={{ height:'8vh',width:'8vw'}} /> <span style={{paddingTop:'2.5vh',fontWeight:500,fontSize:'1.3em'}}>Mom-to-be</span>
</AccordionSummary>
<AccordionDetails>
{MomData}
</AccordionDetails>
</Accordion>
{PregnancyListData && <>
<Accordion >
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel3-content"
id="panel3-header"
>
<img src={Calender} style={{ height:'8vh',width:'8vw'}} /> <span style={{paddingTop:'2.5vh',fontWeight:500,fontSize:'1.3em'}}>Pregnancy Quick List for the Month</span>
</AccordionSummary>
<AccordionDetails>
{/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
malesuada lacus ex, sit amet blandit leo lobortis eget. */}
{/* {PregnancyListData&&Object.keys(PregnancyListData).map((key,value)=>{
return (
<div>{key}{value.toString()}</div>
)
})
} */}
{PregnancyListData&&Object.keys(PregnancyListData).map((key,value)=>{
return (
<div key={key}>
<strong style={{}}>{key}</strong>:{PregnancyListData[key]}</div>
)
})
}
</AccordionDetails>
</Accordion>
</>}
</div>
<div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
{/* <button onClick={takepichandler}>takeyour pic</button> */}
<Typography id="modal-modal-title" variant="h6" component="h2">
Upload file
</Typography>
{/* <button onClick={openCamera}>Open Camera</button> */}
<Typography id="modal-modal-description" sx={{ mt: 2 }} onClick={takePictureHandler}>
<img src={Camera} style={{ height:'4vh',width:'4vw'}} />
<span style={{marginLeft:'2px'}}>Take a Picture</span>
</Typography>
<Typography id="modal-modal-description" sx={{ mt: 2 }} onClick={()=>fileInput.current.click()}>
<img src={Gallery} style={{ height:'4vh',width:'4vw'}} /> <span >Upload from Gallery</span>
<input type="file" ref={fileInput} accept='.jpg,.jpeg,.png' name="file" style={{display:'none'}} onChange={handleFileChange}/>
</Typography>
</Box>
</Modal>
</div>
</>
}
<ToastContainer />
{/* <button onClick={handleUpload}>upload</button> */}
{/* {camera1===true?
<>
<CameraPhoto
onTakePhoto={(dataUri) => { handleTakePhoto(dataUri); }}
onCameraError={(error) => { handleCameraError(error); }}
/>
</>:'not open'
} */}
</div>
)
}
Comments
Post a Comment