I have a problem. I'm creating a small file uploader, that uploads photo. If the user press the icon a file uploader is showing up and then he can select a photo. After selecting the photo isn't showing. Where is exactly the problem?
import React, { useState } from 'react';
const Profilpic = () => {
const [preview, setPreview] = useState(null);
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
if (event.target.files[0].size > 71680) {
alert('File is too big! Wie Samys Dick');
} else {
setPreview(event.target.files[0]);
}
};
return (
<div>
{preview ? (
<img src={preview} alt="Preview" width="150px" height="150px" />
) : (
<div>
<label htmlFor="myInput">
<i className="fas fa-user-circle"></i>
</label>
<input
id="myInput"
style={{ display: 'none' }}
type={'file'}
onChange={fileSelectedHandler}
/>
</div>
)}
</div>
);
};
export default Profilpic;
At first remove the style tag from the input tag then replace the function with that
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
if (event.target.files[0].size > 71680) {
alert("File is too big! Wie Samys Dick");
} else {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onloadend = () => {
setPreview(reader.result);
};
}
};
This will work for you. You just need to create the URL for your selected image.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [preview, setPreview] = useState(null);
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
if (event.target.files[0].size > 71680) {
alert("File is too big! Wie Samys Dick");
} else {
let img = URL.createObjectURL(event.target.files[0]);
setPreview(img);
}
};
console.log(preview);
return (
<div>
{preview ? (
<img src={preview} alt="Preview" />
) : (
<input id="myInput" type="file" onChange={fileSelectedHandler} />
)}
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.