отправка файла с другими данными с помощью axios с реагировать - PullRequest
1 голос
/ 24 октября 2019

Я пытаюсь отправить файл "изображение" с другими параметрами записи, используя axios с библиотекой реагирования, это мой оригинальный код, который очень хорошо работает, отправляя одно изображение или файл на сервер .. на сервере яиспользование библиотеки мультистеров для сохранения изображений:

submitFormImagen(e){
        e.preventDefault();
        const token = localStorage.getItem('auth-token');
        const formData = new FormData();
        formData.append('myImage',this.state.file);

        const config = {
            headers: {
                'content-type': 'multipart/form-data',
                'auth-token': token
            }
        };
        axios.post("http://localhost:5000/api/user/upload",formData,config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response)
                this.setState({imagen: response.data.imagen})
            }).catch((error) => {
        });
    }

в этом случае: formData необходима, чтобы библиотека мультитеров могла сохранить изображение;это мой код с сервера:

router.post('/upload', verificarToken, async function(req,res){
    //imagen nombre: req.file.filename
    console.log(req.body)
    const url = req.protocol + '://' + req.get('host')
    const _id = req.user._id
    upload (req, res, async function(err) {
        if(err) {
            return res.end("Ocurrio un error al subir el archivo.");
        }

        const rutaimagen = url + "/uploads/" +req.file.filename

        //Actualizar Imagen del usuario:
       await User.findByIdAndUpdate(_id, {
            imagen: rutaimagen
        });
        //res.end("Archivo subido correctamente!");
        res.json({imagen: rutaimagen})
    });

  });  

в основном вот и все, теперь я пытаюсь захватить тело запроса, чтобы попытаться обновить изображение пользователя, его имя и адрес электронной почты .. это обновление не работает:

submitFormImagen(e){
        e.preventDefault();
        const token = localStorage.getItem('auth-token');
        const formData = new FormData();
        formData.append('myImage',this.state.file);
        var post = {
            myImage: this.state.file,
            name: this.state.name,
            email: this.state.email
        }
        const config = {
            headers: {
                'content-type': 'multipart/form-data',
                'auth-token': token
            }
        };
        axios.post("http://localhost:5000/api/user/upload",post,config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response)
                this.setState({imagen: response.data.imagen})
            }).catch((error) => {
        });
    }

Также я попытался:

 formData.append('myImage',this.state.file);
    var post = {
        name: this.state.name,
        email: this.state.email
    }
    formData.append('anotherdata',post);
    const config = {
        headers: {
            'content-type': 'multipart/form-data',
            'auth-token': token
        }
    };
    axios.post("http://localhost:5000/api/user/upload",formData,config)
...

и теперь я пытаюсь получить значение «anotherdata» внутри функции загрузки с сервера, который находится внутри маршрута загрузки. но я получил:

[Object: null prototype] { anotherdata: '[object Object]' }

это код сервера:

router.post('/upload', verificarToken, async function(req,res){
    //imagen nombre: req.file.filename

    const url = req.protocol + '://' + req.get('host')
    const _id = req.user._id
    upload (req, res, async function(err) {
        console.log(req.body) //<*********
        if(err) {
            return res.end("Ocurrio un error al subir el archivo.");
        }
...