Reputation: 66
Problem Statement:-
I have written the code to upload an image in React JS. However, I need to send the image data to server and database that's why I need the image data in Byte Array. How can I get the uploaded image data in byte array?
Any help regarding this issue is highly appreciated.
Code:-
import React, { useState } from "react";
import "./style.css";
const ImageUpload = () => {
const [file, setFile] = useState(null);
const [flag, setFlag] = useState(false);
const fileChangedHandler = (event) => {
let file = event.target.files[0];
let reader = new FileReader();
console.log(file);
reader.onload = function (e) {
setFile(e.target.result);
setFlag(true)
};
reader.readAsDataURL(event.target.files[0]);
};
return (
<div id="modeling">
<div className="container">
<div className="row">
<div className="col">
<div className="modeling-text">
</div>
</div>
</div>
{flag ? <img
src={file}
alt={""}
width="190"
height="220"
text-align="left"
style={{ display: "block" }}
/>: <img
src="./Image_Placeholder.jpeg"
alt={""}
width="190"
height="220"
text-align="left"
style={{ display: "block" }}/>}
</div>
<div className="input-group mt-1 offset-1">
<div className="custom-file smaller-input">
<input
type="file"
className="custom-file-input"
name="file"
inputprops={{ accept: "image/*" }}
accept=".png,.jpg,.jpeg"
onChange={fileChangedHandler}
id="inputGroupFile01"
/>
<label className="custom-file-label" htmlFor="inputGroupFile01"> Choose your image
</label>
<i className="bi bi-cloud-upload"></i>
</div>
</div>
</div>
);
};
export default ImageUpload;
Upvotes: 0
Views: 2368
Reputation: 1939
You could use FormData
to send your file to the server.
const formData = new FormData()
if (file) {
formData.append('file', file, file.name)
}
axios.post(`/upload`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
Upvotes: 1