Home > Software design >  Create an Array from for each and array from in ES6
Create an Array from for each and array from in ES6

Time:11-03

I have an input multiple field. I wanted to upload multiple files. My problem is that I wanted to return an array from it.

<input
  id="file"
  type="file"
  accept="image/*"
  multiple
  onChange={(e) => uploadImage(e.currentTarget.files)}
/>;

const uploadImage = (e) => {
  const files = e;

  Array.from(files).forEach((file) => console.log(file));

  const images = files.map((image) => ({
    imageName: image.name,
    imageFile: image,
  }));
  console.log(images);
};

CodePudding user response:

... Returns array (in log) ..:

const uploadImage = (e) => {
    if(!e) return;
    const files = e;
    const fileList = Array.from(files);
    fileList.forEach((file) => console.log(file));

    const images = fileList.map((image) => ({
      imageName: image.name,
      imageFile: image,
    }));
    console.log(images);
  };

  return (
    <>
      <input
        id="file"
        type="file"
        accept="image/*"
        multiple
        onChange={(e) => uploadImage(e.currentTarget.files)}
      />;
  • Related