I want to immediately display the user a file he/she just uploaded in ReactJS. Currently, I am using this code. The image file is not being rendered in the img tag.
( <--PS this is not an issue in image rendering issue in StackOverflow or on your browser. This is how the looks)
import { useState } from 'react';
export default function Upload() {
const [uploadedFile, setuploadedFile] = useState(null);
return (
<div>
<label htmlFor='upload-design'>
{uploadedFile ?
<img src={uploadedFile} /> :
<div>{/* some HTML here*/}</div>}
</label>
<input id='upload-design' type='file' onChange={e => setuploadedFile(e.target.files[0])} />
</div>
)
}
CodePudding user response:
You can't directly show the file input value in <img src=''/> tag.
First you need to convert file input value into base64 then show in <img /> tag
Try below code it's works !
function App() {
const [uploadedFile, setuploadedFile] = useState(null);
const base64FileURL = (element, callback) => {
let file = element;
let reader = new window.FileReader();
reader.onloadend = function (e) {
callback(e.target.result);
};
reader.readAsDataURL(file);
}
const handleFileChange = (file) => {
base64FileURL(file, (obj) => {
setuploadedFile(obj);
});
}
return (
<div>
<label htmlFor='upload-design'>
{uploadedFile ?
<img src={uploadedFile} /> :
<div>{/* some HTML here*/}</div>}
</label>
<input id='upload-design' type='file' onChange={e => handleFileChange(e.target.files[0])} />
</div>
);
};
export default App;
