3

I'm trying to send some files to my api in node.js using multer and when I test with Postman this work well, but when I use my vue app I get "Unexpected field".

Multer's Setup

var storage = multer.diskStorage({
destination: (req, file, cb) => {
  cb(null, 'public/img/products')
},
filename: (req, file, cb) => {
  cb(null, file.originalname)
}
});
var upload = multer({storage: storage}).array('files');

Image Upload

router.post('/NewImageOnProduct/:id', function (req, res) {
upload(req, res, function (err) {
    const files = req.files;
if (err) {
  // An error occurred when uploading
        console.log(err);
        if(!files);
            return res.status(400).send(lang.MissingInfo);

  return res.status(500).send(err);
}

    var newArray = files.map(function(file) {
        return [file.filename, req.params.id];
    });

    pool.query('INSERT INTO tbl_ImagensProdutos (ImagemProduto_nome, produto_id) values ?',
    [
        newArray
    ], function (error, results) {
        if (error) {
            if(error.errno == 1452)
                return res.status(500).send('O produto ao qual está a tentar atribuir uma imagem não existe');
                console.log(error)
            return res.status(500).send(error);
        }
        return res.status(200).send({
            response: "Imagem inserida com sucesso"
        });
    });
// Everything went fine


});
});

Front-end Input

<b-form-file v-model="files" :state="Boolean(files)" placeholder="Choose a file or drop it here..." multiple accept="image/*"></b-form-file>

Upload Function

let formData = new FormData()
  for (var i = 0; i < this.files.length; i++) {
    let file = this.files[i]

    formData.append('files[' + i + ']', file)
  }

  formData.forEach(item => {
    console.log(item)
  })

  this.$api
    .post(`/Admin/products/NewImageOnProduct/` + this.id, formData)
    .then(response => {
      if (response.status === 200) {
        alert(response.data.response)
        this.getDataProducts()
        this.getDataCharacteristicsByProduct()
        this.getProductImages()
        this.resetFormCharacteristics()
      }
    })
    .catch(e => {
      console.log(e.response)

      if (e.response.status == 400) {
        alert('Informação em falta')
        console.log(e.response)
      } else if (e.response.status == 500) {
        console.log(e.response)
        // Colocar mensagem de erro para utilizador repetido
        alert('Erro ao adicionar imagens do produto! \n Tente novamente')
      } else if (e.response.status == 422) {
        console.log(e.response.error)
      }
    })

Postman Picture enter image description here I think is missing something on b-form-file, but I don't know what. If someone could help I'll be grateful

2
  • What is this.$api? Could you show a screenshot of your Postman request parameters? Commented May 11, 2020 at 4:12
  • @Phil I edited and add a screenshot of Postman. this.$api is a axios connection, if you think it's util I can put the code of that too. Commented May 11, 2020 at 4:29

1 Answer 1

4

Multer is expecting an array of files with the fieldname files but you are setting files[0], files[1], etc

Try this in your submit handler

const formData = new FormData()
for (let file of this.files) {
  formData.append('files', file, file.name) // note, no square-brackets
}

Also, in your Axios configuration, make sure you are not setting any Content-type headers for this request. Your browser will take care of that for you when submitting a FormData instance.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, that works. I don't know why I put files[0] in first place. You saved me a lot of hours.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.