Search code examples
file-uploadnuxt.jsvuejs3multipartform-data

Nuxt 3 file upload and store in locally in the project


I want to create a simple Nuxt 3 file upload implementation that stores the file in the locally in a folder in the Nuxt project. In PHP the server side code is very easy and straight forward but I am finding it difficult doing the same thing in Nuxt 3 server side.


Solution

  • I found a better alternative using https://github.com/wobsoriano/h3-formidable

    import { readFiles } from 'h3-formidable';
    import fs from "fs";
    import path from "path";
    
    export default defineEventHandler(async (event) => {
        const { files: { photo: [ { filepath, mimetype } ] } } = await readFiles(event, {
             includeFields: true
        });
    
        let imageName = String(Date.now()) + String(Math.round(Math.random() * 10000000));
        let newPath = `${path.join("public", "uploads", imageName)}.${ mimetype.split('/')[1] }`;
        fs.copyFileSync(filepath, newPath);
    
        return { success: true }
    });