score:101
Try this
<input type="file" onChange={this.onImageChange} className="filetype" id="group_image"/>
Add method to class
onImageChange = (event) => {
if (event.target.files && event.target.files[0]) {
let reader = new FileReader();
reader.onload = (e) => {
this.setState({image: e.target.result});
};
reader.readAsDataURL(event.target.files[0]);
}
}
or you can use URL.createObjectURL
onImageChange = (event) => {
if (event.target.files && event.target.files[0]) {
this.setState({
image: URL.createObjectURL(event.target.files[0])
});
}
}
And display image
<img id="target" src={this.state.image}/>
For the hook version:
const [image, setImage] = useState(null)
const onImageChange = (event) => {
if (event.target.files && event.target.files[0]) {
setImage(URL.createObjectURL(event.target.files[0]));
}
}
return (
<div>
<input type="file" onChange={onImageChange} className="filetype" />
<img src={image} alt="preview image" />
</div>
)
score:2
hope it works for you
<form onSubmit={form => submitForm(form)}>
<input
accept="image/*"
onChange={onImageChange}
className={classes.inputImage}
id="contained-button-file"
multiple
name="image"
type="file"
/>
<label htmlFor="contained-button-file">
<IconButton component="span">
<Avatar
src={mydata.imagePreview}
style={{
margin: "10px",
width: "200px",
height: "200px"
}}
/>
</IconButton>
</label>
<Button
type="submit"
variant="outlined"
className={classes.button}
>
Default
</Button>
</form>
onImageChange
const onImageChange = event => {
if (event.target.files && event.target.files[0]) {
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
setData({
...mydata,
imagePreview: reader.result,
file: file
});
};
reader.readAsDataURL(file);
}
};
submitForm
const submitForm = form => {
form.preventDefault();
const formData = new FormData();
formData.append("image", mydata.file);
// for (var pair of formData.entries()) {
// console.log(pair[1]);
// }
const config = {
headers: {
"content-type": "multipart/form-data"
}
};
axios
.post("api/profile/upload", formData, config)
.then(response => {
alert("The file is successfully uploaded");
})
.catch(error => {});
};
score:4
Recently I came across needing a similar feature. Here is my implementation using hooks
.
export default function App() {
const [image, setImage] = React.useState("");
const imageRef = React.useRef(null);
function useDisplayImage() {
const [result, setResult] = React.useState("");
function uploader(e) {
const imageFile = e.target.files[0];
const reader = new FileReader();
reader.addEventListener("load", (e) => {
setResult(e.target.result);
});
reader.readAsDataURL(imageFile);
}
return { result, uploader };
}
const { result, uploader } = useDisplayImage();
return (
<div className="App">
<input
type="file"
onChange={(e) => {
setImage(e.target.files[0]);
uploader(e);
}}
/>
{result && <img ref={imageRef} src={result} alt="" />}
</div>
);
}
I created a custom hook
so that it can be reused anywhere in the app. The hook
returns the image src
and the uploader
function
.
The image src
can then be linked to the <img src={..} />
and then on input
change you can just pass in the e
to the uploader
function
.
Source: stackoverflow.com
Related Query
- How to display a image selected from input type = file in reactJS
- How to get music's info from input type file in ReactJs
- reactjs how to input multiple file from form
- How to display image in reactjs from laravel storage
- How do I get the actual file from an Input type file element?
- How to display QR code image in React from string type
- How to update a function with useEffect (like componentDidUpdate) and use .map function to display from JSON file ReactJS
- How to display image from mongodb using Reactjs
- How to display corresponding image from selected item in React using hooks
- How can i restrict user from not selecting other file types using input type file with react and typescript?
- how to display image by taking path from .js object in reactjs
- How to display selected Listbox value in ReactJS from state
- ReactJS: How to display selected value from dropdown in input fields?
- How to display image in ReactJS from MongoDB
- How to get image data from a file input in react.js
- How to know which file has been uploaded from multiple inputs of type file in reactjs using Express API
- How to get state value from Input Slider in one JS file to another - ReactJS
- How to Preview Uploaded Image File From File Input with Reactjs?
- How to display selected country details from data.json file on screen when select a particular country from dropdown
- How can i display an image from mongodb in binary with reactjs
- Display an image from url in ReactJS in tsx file
- How do I fix a component is changing from controlled input of the type text to be uncontrolled. Reactjs Error
- How to reset ReactJS file input
- Display an image from url in ReactJS
- How to trigger INPUT FILE event REACTJS by another DOM
- How to get byte array from a file in reactJS
- How to load image from shared file on local server?
- How to display an image which comes back from an axios request (React)?
- How to find display error message from API in reactjs
- How to display IP camera feed from an RTSP url onto reactjs app page?
More Query from same tag
- Error routing user to another component after login
- How to test the style inside the CSS class for React component using Jest and Enzyme?
- map response in back or front
- How to Preview Uploaded Image File From File Input with Reactjs?
- Error: Cannot find module './api/routers'
- ReactJs - Multiple Components - Error: Uncaught ReferenceError: require is not defined
- How can I detect refresh page and routes change in react?
- Is there any way to append start time in ".m3u8" video file
- How to change react styling dependent on condition
- pass props to component in React
- React - Material label not in right position in Textfield
- Configure Mocha to look for `.jsx`/`.es6` files
- ReactJS remove bound event handlers in ES6
- prevent FlowType to check error in node_modules
- Warning message using ant design dynamic form
- Material-UI: DataGrid server-side pagination issue when setting rowCount
- Filtering an ag-grid based on selected row in another ag-grid
- How to set state in a React component using this.setState without explicitly passing the field name to update?
- How do I assign value to the state in react while testing a component?
- is it possible to get the value of input inside the onChange event
- how do you get a pre-loader html code to work in reactjs App?
- Component not rendering with react-router-dom
- Close dropdown in React JS
- How to correctly implement function wrapper in TypeScript?
- why am I getting a runtime error by importing react-chartjs-2
- Change child's state in react
- How to force third party React components to follow styling rules?
- "undefined is not an object" this.state not getting bound
- how to avoid overwriting when inserting todolist task list
- Reactjs: Why child components aren't re-rendering on data change?