How can I properly retrieve files from gatsby-source-filesystem for the end user to download?

Viewed 35

Basically, I'm trying to create a website which allows a user to download documentation files which are added and organized into categories using a .json (gatsby-transformer-json) and sourced for download using gatsby-source-filesystem.

I originally tried accessing the files by placing them in the static folder and using a link with an href of the relative path, for example, <a href={document.relativePath} download>, with the relativePath queried from the .json file (I tried both with subfolders and without). This would work when testing locally with gatsby develop, but when I tested it in a hosted environment, the file it downloaded would be very small and corrupted, and navigating to the expected file url would just redirect to the homepage. I looked into this problem a bit, and the best solution I could find was to import the files before referenceing them in my .js page file, however this solution does not work for me as I am adding files using a .json file which frequently changes during development.

My second attempt involved querying the publicURLs and the relativePaths from the allFile gatsby-source-filesystem query, then creating a dictionary with relativePaths as the key. It was called at the beginning of return() to be processed at build time. The function I ended up creating looked like this:

var LibraryOfURLS = {}

function getPublicURLs() {
  data.allFile.edges.forEach(element => {
    let file = element.node
    LibraryOfURLS[file.relativePath] = file.publicURL
  })
}

However, even though this would get the correct publicURL as queried in allFiles("/static/~random string of letters and numbers~/document.pdf"), the files would still download as corrupted ~50kb pdfs when the site was built and hosted externally (the localhost site actually still did work with this solution as well).

So I guess my question is, how can I retrieve the correct, working path using the filename or relative path as queried in the .json file?

0 Answers
Related