reactjsinputfile-uploadcreateobjecturl

image upload preview: window.URL.createObjectURL() only works once


I have an image uploader built from scratch in a React app. The image preview - made thanks to window.URL.createObjectURL() - only works the first time. I thought it was because of memory issue, so I added window.URL.revokeObjectURL() before each image change. It still does not work.

I've heard about MediaSource() api but I havn't found any exemple for images. What is wrong with this code?

export default function ImageUploader({id, onAdd, onRemove}) {
  const [preview, setPreview] = useState(null);

  const onAddImage = (file: File) => {
    window.URL.revokeObjectURL(preview);
    setPreview(window.URL.createObjectURL(file));
    onAdd(id, file);
  };
  const onRemoveImage = () => {
    window.URL.revokeObjectURL(preview);
    setPreview(null);
    onRemove(id);
  };

  return (
    <div>
      {preview ? <Preview src={preview} alt={id} /> : 
       <Icon icon="upload" />
      }
      <input
        type="file"
        accept="image/png, image/jpeg"
        onChange={(e) => onAddImage(e.target.files[0])}
      />
    </div>
  );
}


Solution

  • the input value not changing, so it wouldn't trigger the onChange function. You can use react useRef hooks api and assign to the input tag and clear the input value inside the onRemoveImage function.