Javascript 使用node js和mongodb服务器与multer的文件上载问题

Javascript 使用node js和mongodb服务器与multer的文件上载问题,javascript,node.js,reactjs,mongodb,Javascript,Node.js,Reactjs,Mongodb,我使用NodeJS、react js和mongodb创建了一个应用程序。我想用multer上传文件,但文件不上传。我与您共享了我为frontent和backend编写的代码块。如何使用multer成功地向mongodb注册imgae。我在网上搜索了很多,但我很困惑。如果能帮上忙,我会很高兴的 型号 const mongoose = require('mongoose'); const Schema = mongoose.Schema; newSchema = new Schema({

我使用NodeJS、react js和mongodb创建了一个应用程序。我想用multer上传文件,但文件不上传。我与您共享了我为frontent和backend编写的代码块。如何使用multer成功地向mongodb注册imgae。我在网上搜索了很多,但我很困惑。如果能帮上忙,我会很高兴的

型号

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

newSchema = new Schema({
    name : String,
    email : String,
    password : String,
    img:{
        type: String
    }
})

module.exports = mongoose.model('User', newSchema)
后端-路由/index.js

const express = require('express')
const User = require('../models/index')
const router = express.Router()
//
const multer = require('multer')
const uuidv4 = require('uuid/v4')
const DIR = './public/';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

//

/* find all users */
router.get('/', (req, res) => {
    User.find({},(err,data) =>{
        res.json(data)
    })
})

/* find user by id */
router.get('/:id',(req, res) =>{
    User.findById(req.params.id, (err, data) =>{
        res.json(data)
    })
})

/* delete user by id */
router.delete('/:id',async (req, res) =>{
    await User.findByIdAndDelete(req.params.id)
    res.json({'message':'deleted'})
})

/* create */
router.post('/',(req,res)=>{
    const url = req.protocol + '://' + req.get('host')
    const user = new User({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password,
        img: url + '/public/' + req.file.filename
    })

    user.save(()=>{
        res.json(user)
    })
})

/* update */
router.put('/:id', async (req, res)=>{
    await User.findByIdAndUpdate(req.params.is, req.body)
    res.json({'message':'updated'})
})

module.exports = router
import React, {Component} from 'react';
import axios from 'axios';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            users: [],
            id: 0,
            name: '',
            email: '',
            password: '',
            img: ''
        }
    }

    componentDidMount() {
        try {
            axios.get('http://localhost:8080/api')
                .then((res) => {
                    this.setState({
                        users: res.data,
                        id: 0,
                        name: '',
                        email: '',
                        password: '',
                        img : ''

                    })
                })
        } catch (e) {
            console.log(e)
        }
    }

    nameChange = event => {
        this.setState({
            name: event.target.value
        })
    }

    emailChange = event => {
        this.setState({
            email: event.target.value
        })
    }

    passwordChange = event => {
        this.setState({
            password: event.target.value
        })
    }

    submit(event, id) {
        event.preventDefault()
        if (id === 0) {
            axios.post('http://localhost:8080/api', {
                name: this.state.name,
                email: this.state.email,
                password: this.state.password,
                img: this.state.img
            }).then(()=>{
                this.componentDidMount()
            })

        } else {
            //axios.put('http://localhost:8080/api/'+id, {
            axios.put('http://localhost:8080/api/${id}', {
                name: this.state.name,
                email: this.state.email,
                password: this.state.password,
                img: this.state.img
            }).then(()=>{
                this.componentDidMount()
            })
        }
    }

    deleteUser(id) {
        try {
            axios.delete('http://localhost:8080/api/' + id)
                .then((res) => {
                    this.componentDidMount()
                })
            console.log('Deleted successfully.')
        } catch (e) {
            console.log(e)
        }
    }

    editUser(id) {
        try {
            axios.get('http://localhost:8080/api/' + id)
                .then((res) => {
                    console.log(res.data)
                    this.setState({
                        id:res.data._id,
                        name: res.data.name,
                        email: res.data.email,
                        password: res.data.password,
                        img: this.state.img
                    })
                })
        } catch (e) {
            console.log(e)
        }
    }

    render() {
        return (
            <div className="row">
                <div className="col s6">
                    <form onSubmit={(e) => this.submit(e, this.state.id)}>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">person</i>
                            <input value={this.state.name} onChange={(e) => this.nameChange(e)} type="text" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Name</label>
                        </div>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">mail</i>
                            <input value={this.state.email} onChange={(e) => this.emailChange(e)} type="email" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Email</label>
                        </div>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">vpn_key</i>
                            <input value={this.state.password} onChange={(e) => this.passwordChange(e)} type="password" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Password</label>
                        </div>
                        <br/>
                        <button className="btn waves-effect waves-light right blue" type="submit" name="action">Submit
                            <i className="material-icons right">send</i>
                        </button>
                        <div>
                            <input type="file" id="myFile" name="filename"/>
                        </div>
                    </form>
                </div>
                <div className="col s6">
                    <table>
                        <thead>
                        <tr>
                            <th>Name Surname</th>
                            <th>Email</th>
                            <th>Password</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        </thead>
                        <tbody>
                        {this.state.users.map(user =>
                            <tr key={user._id}>
                                <td>{user.name}</td>
                                <td>{user.email}</td>
                                <td>{user.password}</td>
                                <td>
                                    <button onClick={(e) => this.editUser(user._id)}
                                            className="btn waves-effect waves-light green" type="submit" name="action">
                                        <i className="material-icons right">edit</i>
                                    </button>
                                </td>
                                <td>
                                    <button onClick={(e) => this.deleteUser(user._id)}
                                            className="btn waves-effect waves-light red" type="submit" name="action">
                                        <i className="material-icons right">delete</i>
                                    </button>
                                </td>
                            </tr>
                        )}
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }

}

export default App;
前端-反应端/App.js

const express = require('express')
const User = require('../models/index')
const router = express.Router()
//
const multer = require('multer')
const uuidv4 = require('uuid/v4')
const DIR = './public/';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
    }
});

//

/* find all users */
router.get('/', (req, res) => {
    User.find({},(err,data) =>{
        res.json(data)
    })
})

/* find user by id */
router.get('/:id',(req, res) =>{
    User.findById(req.params.id, (err, data) =>{
        res.json(data)
    })
})

/* delete user by id */
router.delete('/:id',async (req, res) =>{
    await User.findByIdAndDelete(req.params.id)
    res.json({'message':'deleted'})
})

/* create */
router.post('/',(req,res)=>{
    const url = req.protocol + '://' + req.get('host')
    const user = new User({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password,
        img: url + '/public/' + req.file.filename
    })

    user.save(()=>{
        res.json(user)
    })
})

/* update */
router.put('/:id', async (req, res)=>{
    await User.findByIdAndUpdate(req.params.is, req.body)
    res.json({'message':'updated'})
})

module.exports = router
import React, {Component} from 'react';
import axios from 'axios';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            users: [],
            id: 0,
            name: '',
            email: '',
            password: '',
            img: ''
        }
    }

    componentDidMount() {
        try {
            axios.get('http://localhost:8080/api')
                .then((res) => {
                    this.setState({
                        users: res.data,
                        id: 0,
                        name: '',
                        email: '',
                        password: '',
                        img : ''

                    })
                })
        } catch (e) {
            console.log(e)
        }
    }

    nameChange = event => {
        this.setState({
            name: event.target.value
        })
    }

    emailChange = event => {
        this.setState({
            email: event.target.value
        })
    }

    passwordChange = event => {
        this.setState({
            password: event.target.value
        })
    }

    submit(event, id) {
        event.preventDefault()
        if (id === 0) {
            axios.post('http://localhost:8080/api', {
                name: this.state.name,
                email: this.state.email,
                password: this.state.password,
                img: this.state.img
            }).then(()=>{
                this.componentDidMount()
            })

        } else {
            //axios.put('http://localhost:8080/api/'+id, {
            axios.put('http://localhost:8080/api/${id}', {
                name: this.state.name,
                email: this.state.email,
                password: this.state.password,
                img: this.state.img
            }).then(()=>{
                this.componentDidMount()
            })
        }
    }

    deleteUser(id) {
        try {
            axios.delete('http://localhost:8080/api/' + id)
                .then((res) => {
                    this.componentDidMount()
                })
            console.log('Deleted successfully.')
        } catch (e) {
            console.log(e)
        }
    }

    editUser(id) {
        try {
            axios.get('http://localhost:8080/api/' + id)
                .then((res) => {
                    console.log(res.data)
                    this.setState({
                        id:res.data._id,
                        name: res.data.name,
                        email: res.data.email,
                        password: res.data.password,
                        img: this.state.img
                    })
                })
        } catch (e) {
            console.log(e)
        }
    }

    render() {
        return (
            <div className="row">
                <div className="col s6">
                    <form onSubmit={(e) => this.submit(e, this.state.id)}>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">person</i>
                            <input value={this.state.name} onChange={(e) => this.nameChange(e)} type="text" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Name</label>
                        </div>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">mail</i>
                            <input value={this.state.email} onChange={(e) => this.emailChange(e)} type="email" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Email</label>
                        </div>
                        <div className="input-field col s12">
                            <i className="material-icons prefix">vpn_key</i>
                            <input value={this.state.password} onChange={(e) => this.passwordChange(e)} type="password" id="autocomplete-input"
                                   className="autocomplete" required/>
                            <label htmlFor="autocomplete-input">Password</label>
                        </div>
                        <br/>
                        <button className="btn waves-effect waves-light right blue" type="submit" name="action">Submit
                            <i className="material-icons right">send</i>
                        </button>
                        <div>
                            <input type="file" id="myFile" name="filename"/>
                        </div>
                    </form>
                </div>
                <div className="col s6">
                    <table>
                        <thead>
                        <tr>
                            <th>Name Surname</th>
                            <th>Email</th>
                            <th>Password</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        </thead>
                        <tbody>
                        {this.state.users.map(user =>
                            <tr key={user._id}>
                                <td>{user.name}</td>
                                <td>{user.email}</td>
                                <td>{user.password}</td>
                                <td>
                                    <button onClick={(e) => this.editUser(user._id)}
                                            className="btn waves-effect waves-light green" type="submit" name="action">
                                        <i className="material-icons right">edit</i>
                                    </button>
                                </td>
                                <td>
                                    <button onClick={(e) => this.deleteUser(user._id)}
                                            className="btn waves-effect waves-light red" type="submit" name="action">
                                        <i className="material-icons right">delete</i>
                                    </button>
                                </td>
                            </tr>
                        )}
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }

}

export default App;
import React,{Component}来自'React';
从“axios”导入axios;
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户:[],
id:0,
名称:“”,
电子邮件:“”,
密码:“”,
img:'
}
}
componentDidMount(){
试一试{
axios.get()http://localhost:8080/api')
。然后((res)=>{
这是我的国家({
用户:res.data,
id:0,
名称:“”,
电子邮件:“”,
密码:“”,
img:'
})
})
}捕获(e){
控制台日志(e)
}
}
名称更改=事件=>{
这是我的国家({
名称:event.target.value
})
}
emailChange=事件=>{
这是我的国家({
电子邮件:event.target.value
})
}
passwordChange=event=>{
这是我的国家({
密码:event.target.value
})
}
提交(事件,id){
event.preventDefault()
如果(id==0){
轴心柱http://localhost:8080/api', {
名称:this.state.name,
电子邮件:this.state.email,
密码:this.state.password,
img:this.state.img
}).然后(()=>{
this.componentDidMount()
})
}否则{
//轴心http://localhost:8080/api/“+id{
轴心http://localhost:8080/api/${id}'{
名称:this.state.name,
电子邮件:this.state.email,
密码:this.state.password,
img:this.state.img
}).然后(()=>{
this.componentDidMount()
})
}
}
删除用户(id){
试一试{
axios.delete('http://localhost:8080/api/“+id)
。然后((res)=>{
this.componentDidMount()
})
console.log('已成功删除')
}捕获(e){
控制台日志(e)
}
}
编辑用户(id){
试一试{
axios.get()http://localhost:8080/api/“+id)
。然后((res)=>{
console.log(res.data)
这是我的国家({
id:res.data.\u id,
名称:res.data.name,
电子邮件:res.data.email,
密码:res.data.password,
img:this.state.img
})
})
}捕获(e){
控制台日志(e)
}
}
render(){
返回(
this.submit(e,this.state.id)}>
人
this.nameChange(e)}type=“text”id=“自动完成输入”
className=“自动完成”必填项/>
名称
邮件
this.emailChange(e)}type=“email”id=“自动完成输入”
className=“自动完成”必填项/>
电子邮件
vpn_密钥
this.passwordChange(e)}type=“password”id=“自动完成输入”
className=“自动完成”必填项/>
密码

提交 发送 姓名 电子邮件 密码 编辑 删除 {this.state.users.map(user=> {user.name} {user.email} {user.password} this.editUser(user.\u id)} className=“btn波浪效果波浪浅绿色”type=“提交”name=“操作”> 编辑 this.deleteUser(user.\u id)} className=“btn波浪效果波浪浅红色”type=“提交”name=“操作”> 删除 )} ); } } 导出默认应用程序;
将文件(已转换为字符串)上载到MongoDB.I w不是一个好做法