0

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.
enter image description here enter image description here( <--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>
    )
}

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.