Samriddha Bajpai
Samriddha Bajpai

Reputation: 66

Need image in the form of Byte Array in React JS

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

Answers (1)

Georgy
Georgy

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

Related Questions