expressjs / multer

Node.js middleware for handling `multipart/form-data`.
MIT License
11.63k stars 1.06k forks source link

Requests made through pinia display 'MulterError: Unexpected field at wrappedFileFilter' #1257

Closed sooooooooooooooooootheby closed 5 months ago

sooooooooooooooooootheby commented 7 months ago

There is nothing error with using html forms, but requests made through pinia will get 'MulterError: Unexpected field att wrappedFileFilter'

// Front-end(pinia)
async postCover() {
            try {
                console.log(1);
                // const post_cover = this.postCover;
                const formData = new FormData();
                formData.append('post_cover', this.cover);

                const res = await axios.post('/api/cover', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
            } catch(error) {
                console.log(error);
            }
        }
// back-end(node.js)
const multer = require("multer");
const upload = multer({ dest: "uploads/" });

router.post("/cover", upload.single("cover"), async (req, res) => {
    console.log(1);
    res.send(req.file);
});

PixPin_2024-05-01_20-47-01

BeinRain06 commented 5 months ago

I bump into the same issue using pinia store for input file

I manage rewritng a ref() input (called inputFile) with and set the name of the input in <template></template>tag as name="file"

here is what i have done in front end app :

`<template>
  <div class="form_control">
            <label for="image">Image</label>
            <input
              type="file"
              id="image"
              name="file" // <-- here
              accept="image/png, image/jpeg, image/webp"
              ref="inputFile" // <-- here
            />
  </div>

</template>`

script

`<script setup>
  import { ref } from 'vue'

  const inputFile = ref(null) <-- Here

  async function createPost() {
    const myInputFile = inputFile.value  //reactivity fundamentals

    //send img post
  const image = await primarimageapi(myInputFile)
  }
</script>`

On the api function primarimageapi i make this:

`export const primarimageapi = async (myInputFile) => {
  try {
    const file = myInputFile.files[0]   <--   Here File Grabbed

    //formData instance
    const formData = new FormData()

    //add element
    formData.append('file', file)

    const prePostImg = await fetch(`${base_url}/post/image/create`, {
      method: 'POST',
      body: formData
    })
      .then((res) => res.json())
      .then((newres) => newres.image_url)

      return prePostImg
   } catch (err) {
    console.log(err)}}`

my blog-app three elements was organized like below:

`blog*app --|
            |
            |* \_ _client
            |
            |
            |_ \_ _server
            |
            |_ _src
                  |
                  |_ _public
                  | |
                  | |_ _images
                  |
                  |
                  |_ _routes
                            |
                            |_ \_post-routes.js (file)`

In post-route.js file i wrote this :

//multer

`const storage = multer.diskStorage({destination: function (req, file, callback) {
callback(null, path.join(__dirname, "../public/images"));
},
filename: function (req, file, callback) {
const filename = `${file.fieldname}_${Date.now()}${path.extname(
  file.originalname
)}`;

callback(null, filename);},
})

const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 },
  });
`

//middleware destination image - express

`router.use(`/images`, express.static(path.join(__dirname, "../public/images")))`

//router

`router.post("/image/create", upload.single("file"), (req, res) => {
  try {
    const base_url = process.env.API_URL;

    res.status(200).json({
      success: true,
      image_url: `/${base_url}/images/${req.file.filename}`,
    });
    } catch (err) {
      console.log(err);
      }
 })`

then i obtain inside src/public/images my first image : file_1717587794699.jpg

sooooooooooooooooootheby commented 5 months ago

Looking your code, I found that the problem was in my middleware. now, The problem was solved. thank you and your code.