0
votes

I am trying to upload a filename and a post (9 gag style) to my mysql database, and store the file into my project folder. I am getting the file from the front end (console.log in the front works perfectly), then i Use nodejs + express backend to handle the file and send it to my database. I created a multer middleware to set the filename, extension, disk location, then in a controller i am trying to get the file to send it do database. The console.log "route ok" is fine, but when i console.log req.file or req.file.filename, or req.body.file, etc... I get an undefined answer... I really don't see what is wrong with my code, I already used it in another projet i worked fine but i was doing only the backend.

Here is my front end code (vue js) :

<template>
    <div id="container">
        <div id="formPost">
            <button class="btn btn-primary" @click.prevent="displayFormPost = !displayFormPost">Créer un post</button>
            <form v-if="displayFormPost">
            <input type="text" class="form-control" placeholder="Entrer la description de l'image" v-model="messageToPost">
            <input type="file" ref="file">  <button class="btn btn-primary" @click.prevent="postMessage">Poster</button>
        </form>
        </div> 
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data() {
        return {
            displayFormPost: false,
            messageToPost: ''
        }
    }, 
    methods: {
        postMessage() {
            let file = this.$refs.file.files[0];
            let message = this.messageToPost; 
            console.log(file);
            axios.post('http://localhost:3000/wall/post/', { message , file } )
            .then(response => {
                console.log(response);
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
}
</script>

My multer-config middleware :

const MIME_TYPES = {
    'image/jpg': 'jpg', 
    'image/jpeg': 'jpg', 
    'image/png': 'png', 
    'image/gif': 'gif'
}

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, 'images')
    }, 
    filename: (req, file, callback) => {
        const name = file.originalname.split(' ').join('_');
        const extension = MIME_TYPES[files.mimetype];
        callback(null, name + Date.now() + '.' + extension);
    }
})

module.exports = multer({ storage }).single('image'); 

and my controller (i have been just trying to display filename etc so far) :

exports.postMessage = (req, res, next) => {
    console.log(req.file)
    console.log('routeok');
}

And my routes set with multer :

const express = require('express');
const router = express.Router();
const multer = require('../middleware/multer-config');

const wallControllers = require('../controllers/wall');

router.post('/post/', multer, wallControllers.postMessage);

module.exports = router; 

Ps : no error in the console at all

Thank you !!

1
A relevant code snippet is missing: how do you integrate multer and your controller into your Node app?juzraai
Just added it. Thank you for the feedbackMikev60

1 Answers

1
votes

I think there are 2 issues:

First of all, when you set up multer you tell it to expect the file in a field named "image":

multer({ storage }).single('image');

But you never name any field as "image", not in the HTML, nor when you call axios.

Also, to send a file, you must set a proper Content-Type HTTP header and you should use the FormData API, as described in this answer.

So you may try:

const formData = new FormData();
formData.append("image", file);
formData.append("message", message);
axios.post('http://localhost:3000/wall/post/', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})