nuxt-file-storage
nuxt-file-storage

在 Nuxt 应用中存储文件的简单解决方案。从前端上传文件,并在后端接收文件,以将文件保存到您的项目中。

Nuxt File Storage Banner

Nuxt 文件存储

Visits Badge npm version npm downloads License Nuxt

在您的 Nuxt 应用中存储文件的简单解决方案。能够从前端上传文件,并在后端接收文件,然后将文件保存到您的项目中。

功能

  • 📁  从文件输入中获取文件并准备发送到后端
  • ⚗️  在后端序列化文件以便能够适当地使用它们
  • 🖴  使用 Nitro 引擎将文件存储在 Nuxt 后端中的指定位置

快速设置

  1. nuxt-file-storage 依赖项添加到您的项目
# 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. nuxt-file-storage 添加到 nuxt.config.tsmodules 部分
export default defineNuxtConfig({
    modules: ['nuxt-file-storage'],
})

就是这样!您现在可以在 Nuxt 应用中使用 Nuxt 存储了 ✨

配置

您目前可以配置 nuxt-file-storage 模块的一个设置。以下是配置接口

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
    },
})

使用

在前端处理文件

您可以使用 Nuxt 存储从 <input> 标签获取文件

<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>

files 返回一个包含文件的 ref 对象

handleFileInput 返回一个 Promise,以防您需要检查文件输入是否已完成


以下是一个使用文件将其发送到后端的示例

<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>

处理多个文件输入字段

您必须为每个输入字段创建一个新的 useFileStorage 实例

<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>

通过调用新的 useFileStorage 实例,您可以将输入之间的内部逻辑分开

在后端处理文件

使用 Nitro Server Engine,我们将创建一个 API 路由,接收文件并将它们存储在 userFiles 文件夹中

import { ServerFile } from "nuxt-file-storage";

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
    await getFileLocally('requiredFile.txt', '/userFiles')
    // returns: {AbsolutePath}/userFiles/requiredFile.txt

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

就是这样!现在您可以将用户上传的任何文件存储到您的 Nuxt 项目中 ✨

贡献

遇到问题?打开一个新问题。我将尽力包含所有请求的功能,如果它们符合项目范围。

想添加一些功能?欢迎 PR!

  • 克隆此仓库
  • 安装依赖
  • 准备项目
  • 运行开发服务器
git clone https://github.com/NyllRE/nuxt-file-storage && cd nuxt-file-storage
npm i
npm run dev:prepare
npm run dev