问题
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