0

i tried to implement the solution which was posted here formidable is installed and exposed/loaded via nuxtconfig file.

my index.post looks exactly like this:

import formidable from "formidable";
import fs from "fs";
import path from "path";

export default defineEventHandler(async (event) => {
  let imageUrl = "";
  let oldPath = "";
  let newPath = "";

  const form = formidable({ multiples: true });
  const data = await new Promise((resolve, reject) => {
    form.parse(event.req, (err, fields, files) => {
      if (err) {
        reject(err);
      }
      if (!files.photo) {
        resolve({
          status: "error",
          message: "Please upload a photo with name photo in the form",
        });
      }
      if (files.photo.mimetype.startsWith("image/")) {
        let imageName =
          Date.now() +
          Math.round(Math.random() * 100000) +
          files.photo.originalFilename;
        oldPath = files.photo.filepath;
        newPath = `${path.join("public", "uploads", imageName)}`;
        imageUrl = "./public/upload/" + imageName;
        fs.copyFileSync(oldPath, newPath);
        resolve({
          status: "ok",
          url: imageUrl,
        });
      } else {
        resolve({
          status: "error",
          message: "Please upload nothing but images.",
        });
      }
    });
  });
  return data;
});

this is the frontend part:

<template>
  <v-col cols="12" sm="10">
    <v-sheet min-height="70vh" rounded="lg" class="pa-3">
      <input
        type="file"
        accept="image/*"
        label="Bild hochladen"
        @change="onChange"
      />
    </v-sheet>
  </v-col>
</template>

<script setup lang="ts">
const onChange = async (e: Event) => {
  const selectedFile = e.target.files[0]

  const formData = new FormData()
  formData.append('file', selectedFile)

  await useAsyncData('file', () =>
    $fetch(`/api/v1/data/images`, {
      method: 'POST',
      body: formData,
    })
  )
}
</script>

I am getting the error:

[nitro] [dev] [uncaughtException] TypeError: Cannot read properties of undefined (reading 'mimetype') 18:57:47 at file:///home/user/repo/test-store/packages/store/.nuxt/dev/index.mjs:873:23 at zalgoSafe (/home/user/repo/test-store/node_modules/dezalgo/dezalgo.js:20:10) at f (/home/user/repo/test-store/node_modules/once/once.js:25:25) at IncomingForm. (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:183:9) at IncomingForm.emit (node:events:513:28) at IncomingForm._maybeEnd (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:612:10) at /home/user/repo/test-store/node_modules/formidable/src/Formidable.js:390:14 at Array. (/home/user/repo/test-store/node_modules/formidable/src/PersistentFile.js:77:7) at finish (node:internal/streams/writable:745:25) at finishMaybe (node:internal/streams/writable:733:9

I run in similar issues before. there are differences from the RC version to the final released version. any solution for this?

I have tried to implement a solution with the fs module. here I am struggling too...

export default defineEventHandler(async (event) => {
  const {imageName} = event.context.params

  const body = await readBody(event)

  await saveFile(body)

  async function saveFile(file) {
    console.log('Saving file 2')
    fs.writeFileSync(`./assets/article/images/${imageName}`, file)
    return
  }
})

This seems to partially work. But the generated file is corrupted.

kissu
  • 40,416
  • 14
  • 65
  • 133
quei
  • 13
  • 2

0 Answers0