How do we handle image with filepath and convert to base64 in react hooks

牧云@^-^@ 提交于 2020-06-29 03:22:25

问题


How do we handle and convert into base64, if we receive image with path in React Hook in following format: images\photo-1592376542020.JPG

UserLoginProvider.js

import { UserProfileContext, UserLoginContext } from '../context';

const UserLoginProvider = ({children}) => {

    const [loginPhoto, setLoginPhoto] = useState({ photo:''});

     const value = useMemo(() => ({
        loginPhoto, setLoginPhoto
    }), [loginPhoto]);


    return (
       <UserLoginContext.Provider value={value}>
           {children}
       </UserLoginContext.Provider>
    )   
}
export default UserLoginProvider;

Navigation.js

const [loginImgSrc, setLoginImgSrc] = useState(null);
const { loginPhoto } = useContext(UserLoginContext);

// While doing console.log("Print here:"+loginPhoto);  displays [object object ] 
    useEffect(() => {
            if (loginPhoto.photo) {
            const reader = new FileReader();
            reader.addEventListener('load', () => {
               setLoginImgSrc(reader.result);
               console.log("LoginImage:"+reader.result);
               localStorage.setItem("loginImgData", reader.result);
            });
            reader.readAsDataURL(loginPhoto.photo);
            }
        }, [loginPhoto.photo])

        var loginImage = localStorage.getItem('loginImgData');

<span className="image_login_link"><img className="nav_profile" src={loginImage}></img></span>

来源:https://stackoverflow.com/questions/62443325/how-do-we-handle-image-with-filepath-and-convert-to-base64-in-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!