0

I write this code for preview image before upload but the problem I can either preview image or get image file. I can't get both functionality at a time preview image and file for upload. If I replace return URL.createObjectURL(file); to retun file then I am getting file for upload but image preview not working. How to use both functionality ? any suggestion? here is my code:

export const MultiImageUpload = () => {
  const [selectedImages, setSelectedImages] = useState([]);

  const onSelectFile = (event) => {
    const selectedFiles = event.target.files;
    const selectedFilesArray = Array.from(selectedFiles);
 
     
    const imagesArray = selectedFilesArray.map((file) => {
      
      return URL.createObjectURL(file);
      //return file 
      
    });
    
   
     
    setSelectedImages((previousImages) => previousImages.concat(imagesArray));
    
    
    // FOR BUG IN CHROME
    event.target.value = "";
  };

  function deleteHandler(image) {
    setSelectedImages(selectedImages.filter((e) => e !== image));

    URL.revokeObjectURL(image);
  }

1 Answer 1

1

Well you can use both url (base64 string )and file (blob) at the same time,Like this

//this will  hold base64 url of images
const [selectedImagesURL, setSelectedImagesURL] = useState([]);
//this will hold file blob
const [selectedImages, setSelectedImages] = useState([]);

Now your on change handler should updated both url and images array

const onSelectFile = (event) => {
const selectedFiles = event.target.files;
const selectedFilesArray = Array.from(selectedFiles);
const imagesURLArray = selectedFilesArray.map((file) => {
  return URL.createObjectURL(file);
});
 
setSelectedImages((previousImages) => previousImages.concat(selectedFilesArray));
setSelectedImagesURL((previousImagesURL) => previousImagesURL.concat(imagesURLArray));


// FOR BUG IN CHROME
event.target.value = "";
};

Then use selectedImagesURL to preview the images and selectedImages to upload.

Hope this will help!

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.