37
loading...
This website collects cookies to deliver better user experience
multer
from our file uploading.But in some case when we are doing a demo project or practicing some thing then if i have to setup whole multer code base then it is horrible.For that today i am going to show you how can you upload a file using a react package called react-file-base64
.$ cd Desktop
$ mkdir react-file-upload
$ cd react-file-upload
$ npx create-react-app ./ --template typescript
App.tsx
file importimport FileBase from 'react-file-base64'
<form onSubmit={handleSubmit}>
<FileBase/>
<button type="submit">Send</button>
<div>
<img src='' alt="react project" />
</div>
</form>
state
and change handler for controlling the formtype State = {
image: string;
};
const [data, setData] = useState<State>({
image: "",
});
const [image, setImage] = useState("");
const handleSubmit = (e: React.SyntheticEvent) => {
e.preventDefault();
};
FileBase
Component they are type,multiple,onDone
.So,give them to FileBase<FileBase
type="file"
multiple={false}
onDone={({ base64 }: { base64: string }) =>
setData({ ...data, image: base64 })
}
/>
onDone
works same as onChange
.onDone receives a parameter which contains base64
.You should console log that parameter to see what the parameter contains.Now set base64
to the state.data
form onSubmit
handlerconst handleSubmit = (e: React.SyntheticEvent) => {
e.preventDefault();
console.log(data);
};
image
property contains something like string.This string goes into src
attribute of an img
element.<img src={image ? image : ""} alt="react project" />
const handleSubmit = (e: React.SyntheticEvent) => {
e.preventDefault();
setImage(data.image);
};