MCPcopy Index your code
hub / github.com/NyllRE/nuxt-file-storage

github.com/NyllRE/nuxt-file-storage @v0.3.3

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.3.3 ↗ · + Follow
25 symbols 96 edges 17 files 0 documented · 0%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Nuxt File Storage Banner

Nuxt File Storage

npm version npm downloads License nuxt.care health Nuxt

Easy solution to store files in your nuxt apps. Be able to upload files from the frontend and receive them from the backend to then save the files in your project.

Features

  • 📁  Get files from file input and make them ready to send to backend
  • ⚗️  Serialize files in the backend to be able to use them appropriately
  • 🖴  Store files in a specified location in your Nuxt backend with Nitro Engine

Quick Setup

  1. Add nuxt-file-storage dependency to your project
# Using pnpm
pnpm add -D nuxt-file-storage

# Using yarn
yarn add --dev nuxt-file-storage

# Using npm
npm install --save-dev nuxt-file-storage
  1. Add nuxt-file-storage to the modules section of nuxt.config.ts
export default defineNuxtConfig({
    modules: ['nuxt-file-storage'],
})

That's it! You can now use Nuxt Storage in your Nuxt app ✨

Configuration

You can currently configure a single setting of the nuxt-file-storage module. Here is the config interface:

export default defineNuxtConfig({
    modules: ['nuxt-file-storage'],
    fileStorage: {
        // enter the absolute path to the location of your storage
        mount: '/home/$USR/development/nuxt-file-storage/server/files',

        // {OR} use environment variables (recommended)
        mount: process.env.mount
        // you need to set the mount in your .env file at the root of your project
    },
})

Usage

Handling Files in the frontend

You can use Nuxt Storage to get the files from the <input> tag:

<template>
    <input type="file" @input="handleFileInput" />
</template>

<script setup>
    // handleFileInput can handle multiple files
    // clearOldFiles: true by default, each time the user adds files the `files` ref will be cleared
    const { handleFileInput, files } = useFileStorage({ clearOldFiles: false })
</script>

The files return a ref object that contains the files

The clearFiles function empties the files list without needing to reassign files.value = []. It also accepts an optional Ref<HTMLInputElement | null> to clear the file input element in the DOM:

<template>
    <input type="file" ref="fileInputRef" @input="handleFileInput" multiple />
    <button @click="clearFiles(fileInputRef)">Clear</button>
</template>

<script setup>
const fileInputRef = ref<HTMLInputElement | null>(null)
const { handleFileInput, clearFiles } = useFileStorage()
</script>

handleFileInput returns a promise in case you need to check if the file input has concluded

Here's an example of using files to send them to the backend

<template>
    <input type="file" @input="handleFileInput" />
    <button @click="submit">submit</button>
</template>

<script setup>
const { handleFileInput, files } = useFileStorage()

const submit = async () => {
    const response = await $fetch('/api/files', {
        method: 'POST',
        body: {
            files: files.value
        }
    })
}
</script>

Handling multiple file input fields

You have to create a new instance of useFileStorage for each input field

<template>
    <input type="file" @input="handleFileInput" multiple />   ← | 1 |
    <input type="file" @input="profileInputHandler" />                 ← | 2 |
</template>

<script setup>
    const { handleFileInput, files } = useFileStorage()       ← | 1 |

    const {
        handleFileInput: profileInputHandler,
        files: profileImage
    } = useFileStorage()                                               ← | 2 |
</script>

by calling a new useFileStorage instance you separate the internal logic between the inputs

Using with defineExpose

The files ref is iterable, so it works naturally with defineExpose in child components:


<template>
    <input type="file" @input="handleFileInput" multiple />
</template>

<script setup>
const { handleFileInput, files, clearFiles } = useFileStorage()

defineExpose({
    files,
    handleFileInput,
    clearFiles,
})
</script>

<template>
    <ChildComponent ref="childRef" />
    <button @click="iterateFiles">Show Files</button>
</template>

<script setup>
const childRef = ref()

const iterateFiles = () => {
    // Direct iteration — no double .value needed
    for (const file of childRef.value.files) {
        console.log(file.name)
    }

    // Traditional .value access still works
    console.log(childRef.value.files.value)
}
</script>

Handling files in the backend

using Nitro Server Engine, we will make an api route that receives the files and stores them in the folder userFiles

import { ServerFile } from "#file-storage/types";

export default defineEventHandler(async (event) => {
    const { files } = await readBody<{ files: ServerFile[] }>(event)

    for ( const file of files ) {
        await storeFileLocally(
            file,         // the file object
            8,            // you can add a name for the file or length of Unique ID that will be automatically generated!
            '/userFiles'  // the folder the file will be stored in
        )

        // {OR}

        // Parses a data URL and returns an object with the binary data and the file extension.
        const { binaryString, ext } = parseDataUrl(file.content)
    }

    // Deleting Files
    await deleteFile('requiredFile.txt', '/userFiles')

    // Get file path
    return await getFileLocally('requiredFile.txt', '/userFiles')
    // returns: {AbsolutePath}/userFiles/requiredFile.txt

    // Return a NodeStream of the file
    // uses getFileLocally internally
    return await retrieveFileLocally(event, 'requiredFile.txt', '/userFiles')

    // Get all files in a folder
    return await getFilesLocally('/userFiles')
})

And that's it! Now you can store any file in your nuxt project from the user ✨

Contribution

Run into a problem? Open a new issue. I'll try my best to include all the features requested if it is fitting to the scope of the project.

Want to add some feature? PRs are welcome! - Clone this repository - install the dependencies - prepare the project - run dev server

git clone https://github.com/NyllRE/nuxt-file-storage && cd nuxt-file-storage
npm i
npm run dev:prepare
npm run dev

Extension points exported contracts — how you extend this code

File (Interface)
(no doc)
test/fixtures/basic/server/api/files.ts
ServerFile (Interface)
(no doc)
src/runtime/types.ts
ClientFile (Interface)
(no doc)
src/runtime/types.ts
ModuleOptions (Interface)
(no doc)
src/runtime/types.ts

Core symbols most depended-on inside this repo

storeFileLocally
called by 22
src/runtime/server/utils/storage.ts
resolveAndEnsureInside
called by 7
src/runtime/server/utils/path-safety.ts
normalizeRelative
called by 6
src/runtime/server/utils/path-safety.ts
isSafeBasename
called by 5
src/runtime/server/utils/path-safety.ts
ensureSafeBasename
called by 5
src/runtime/server/utils/path-safety.ts
createError
called by 4
test/__mocks__/imports.ts
getMount
called by 4
src/runtime/server/utils/storage.ts
getFileLocally
called by 3
src/runtime/server/utils/storage.ts

Shape

Function 21
Interface 4

Languages

TypeScript100%

Modules by API surface

src/runtime/server/utils/storage.ts8 symbols
src/runtime/server/utils/path-safety.ts5 symbols
src/runtime/composables/useFileStorage.ts4 symbols
src/runtime/types.ts3 symbols
test/__mocks__/imports.ts2 symbols
test/storage.test.ts1 symbols
test/fixtures/basic/server/api/files.ts1 symbols
src/module.ts1 symbols

For agents

$ claude mcp add nuxt-file-storage \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact