简体   繁体   中英

Get the downloadURL for each file from firebase storage

I'm trying to get the downloadURL for each file from the firebase storage. Currently I'm displaying the metadata (in this case the name of each file).

  const [fileNames, setFileNames] = useState([]);

  useEffect(() => {
    const getFiles = async () => {
      const storage = await firebase.storage().ref("/recursos");
      const list = await storage.listAll();
      const items = list.items.map((ref) => ref.getMetadata());
      const results = await Promise.all(items);
      setFileNames(results);
    };
    getFiles();
  }, []);

  return (
    <div className="home">
      <SinapseNav />
      <Container className="d-flex align-items-center justify-content-center mt-4 mb-4">
        <Card className="home-card">
          <Card.Body>
            <h3 className="text-center mb-4">Pesquisar Recursos</h3>
            <Form.Control placeholder='Ex: "Trigonometria"' />

            {fileNames.map((file) => {
              return (
                <Container key={file.name}>
                  <ResourceCard title={file.name} />
                </Container>
              );
            })}
          </Card.Body>
        </Card>
      </Container>
    </div>
  );
} 

As explained in the doc , you can call getDownloadUrl() on the items of the ListResult you got through listAll() . Exactly the same way than you do with getMetadata() .

So the following should do the trick:

const getUrls = async () => {
  const storage = firebase.storage().ref("/recursos");
  const list = await storage.listAll();
  const items = list.items.map((ref) => ref.getDownloadUrl());
  const urls = await Promise.all(items);
  // Do whatever you want with the urls Array
};

Note that listAll() has a default pagination size is 1000: It is actually a "helper method for calling list() repeatedly until there are no more results".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM