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