nuxt-file-storage
nuxt-file-storage
Nuxtアプリケーションでファイルを保存するための簡単なソリューションです。フロントエンドからファイルをアップロードし、バックエンドからファイルを受け取ってプロジェクトに保存します。
Nuxtファイルストレージ
Nuxtアプリケーションでファイルを保存するための簡単なソリューションです。フロントエンドからファイルをアップロードし、バックエンドからファイルを受け取ってプロジェクトに保存できます。
機能
- 📁 ファイル入力からファイルを取得し、バックエンドに送信する準備をします
- ⚗️ バックエンドでファイルをシリアライズして、適切に使用できるようにします
- 🖴 Nitroエンジンを使用して、Nuxtバックエンドの指定された場所にファイルを保存します
クイックセットアップ
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
nuxt.config.ts
のmodules
セクションにnuxt-file-storage
を追加します
export default defineNuxtConfig({
modules: ['nuxt-file-storage'],
})
これで完了です! NuxtアプリケーションでNuxt Storageを使用できるようになりました ✨
設定
現在、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 Storageを使用して、<input>
タグからファイルを取得できます
<template>
<input type="file" @input="handleFileInput" />
</template>
<script setup>
// handleFileInput can handle multiple files
const { handleFileInput, files } = useFileStorage()
</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>
バックエンドでのファイルの処理
Nitroサーバーエンジンを使用して、ファイルを受信し、userFiles
フォルダーに保存するAPIルートを作成します
export default defineEventHandler(async (event) => {
const { files } = await readBody<{ files: File[] }>(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)
}
return 'success!'
})
interface File {
name: string
content: string
}
これで完了です! ユーザーからNuxtプロジェクトに任意のファイルを保存できるようになりました ✨
貢献
問題が発生しましたか? 新しい issue を開いてください。プロジェクトの範囲に合致する場合、リクエストされたすべての機能を含めるように最善を尽くします。
機能を追加したいですか? PRは大歓迎です!
- このリポジトリをクローンします
- 依存関係をインストールします
- プロジェクトを準備します
- 開発サーバーを実行します
git clone https://github.com/NyllRE/nuxt-file-storage && cd nuxt-file-storage
npm i
npm run dev:prepare
npm run dev