简体   繁体   中英

Gatsby GraphQL download multiple images at once

This query

query MyQuery {
  allStrapiLogos {
    nodes {
      id
      Image {
        localFile {
          publicURL
        }
      }
    }
  }
}

provides the following result:

{
  "data": {
    "allStrapiLogos": {
      "nodes": [
        {
          "id": "Logos_1",
          "Image": [
            {
              "localFile": {
                "publicURL": "someUrl.png"
              }
            },
            {
              "localFile": {
                "publicURL": "someUrl.png"
              }
            }
          ]
        },
        {
          "id": "Logos_2",
          "Image": [
            {
              "localFile": {
                "publicURL": "/someUrl.png"
              }
            }
          ]
        },
        {
          "id": "Logos_3",
          "Image": [
            {
              "localFile": {
                "publicURL": "someUrl.svg"
              }
            }
          ]
        }
      ]
    }
  },
  "extensions": {}
}

Usually, what I did was going on like this:

  <Link to={publicURL}>
          <ReactSVG wrapper="span" src={svgIcons.download} style={{ paddingRight: '16px' }} />
        </Link>

this always worked for 1 file. I am unsure what the best approach would be to tackle downloading multiple images at once.
The GraphQL queries are generated by the gatsby-source-plugin . Any ideas?

So my issue is that I do not know how a user can download all the images by clicking on a link.

Given that scenario, I would recommend avoiding the Link component, since doesn't fit your requirements.

I would do something like:

  <button onClick={downloadAllItems}>Download</button>

Then, in your function:

  const downloadAllItems=()=>{
    data.allStrapiLogos.nodes.forEach(node=> window.open(`/yoursite.com/${node.Image.localFile.publicUrl}`))
  }

Modified from:

Add an event.preventDefault before the loop if the button is inside a form to avoid unwanted requests if needed.

Given your use-case, I think is the more intuitive approach to download all items in one-click function.

You can bypass browser's (or adblock's) limitation by setting the window.open and save the memory reference and setting the location on the callback:

let newWindow=window.open(...)

Then:

newWindow.location=`/yoursite.com/${node.Image.localFile.publicUrl}`

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