#Download files from website directory (Next.JS)

1 messages · Page 1 of 1 (latest)

sturdy mountainBOT
#

Hi @wintry jetty. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To download files from your website directory in Next.js, you can use the built-in capability of Next.js to serve static files. This is done by placing your files under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

For example, if you add file.pdf inside public, you can access the file at the URL <http://yourwebsite.com/file.pdf.>

Here's an example of how you can use an image file placed in the public directory:

import Image from 'next/image'
 
export function Avatar() {
 return <Image src="/me.png" alt="me" width="64" height="64" />
}

In this example, me.png is an image file located in the public directory.

Please note:

  • The directory must be named public. The name cannot be changed and it's the only directory used to serve static assets.
  • Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available.

For persistent file storage, it's recommended to use a third-party service like AWS S3.

For more details, you can refer to the Next.js documentation on static file serving (https://nextjs.org/docs/basic-features/static-file-serving).

If you want to read files from the filesystem in getStaticProps, you can use process.cwd() which gives you the directory where Next.js is being executed. Here's an example:

#
import { promises as fs } from 'fs'
import path from 'path'
 
export async function getStaticProps() {
 const postsDirectory = path.join(process.cwd(), 'posts')
 const filenames = await fs.readdir(postsDirectory)
 
 const posts = filenames.map(async (filename) => {
 const filePath = path.join(postsDirectory, filename)
 const fileContents = await fs.readFile(filePath, 'utf8')
 
 return {
 filename,
 content: fileContents,
 }
 })
 return {
 props: {
 posts: await Promise.all(posts),
 },
 }
}

In this example, files are read from a directory named posts located in the root directory of your project. The getStaticProps function is called at build time on the server-side, and it won't be called on the client-side.

For more details, you can refer to the Next.js documentation on getStaticProps (https://nextjs.org/docs/pages/api-reference/functions/get-static-props).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: