【问题标题】:React upload file to mongodb node Js multerReact 上传文件到 mongodb 节点 Js multer
【发布时间】:2020-07-16 06:23:47
【问题描述】:

我正在尝试将图像从反应组件上传到 mongodb 数据库。我已经尝试了所有可能的方法,但后端在控制台中返回未定义。这是我正在努力的代码 首先是反应形式

<div className="md:w-1/2 h-7 m-auto mt-8 border-gray-900 rounded shadow-md">
    <form encType='multipart/form-data' className="m-auto text-center rounded h-auto px-8 border-gray-900">
      <div className="inline-block container m-auto pb-6 flex items-center py-2">
        <input className='hidden' name='StudentImage' type="file" onChange={this.fileSelectedHandler}
      </div>
      </div>

    </form>
  </div>

然后是选择处理程序

fileSelectedHandler = e => {
    console.log(e.target.files[0]);
    this.setState({
      StudentImage: e.target.files[0]
    });
    const data = new FormData() 
    data.append('StudentImage', this.state.StudentImage);
    axios.post('http://localhost:4000/students/image',data)
    console.log(this.state.StudentImage.lastModified)
  };

和nodejs后端代码

    destination: function (req, file, cb) {
      cb(null, 'assets/images')
    },
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
    }
  })

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') {
        cb(null, true);
    } else {
        cb(null, false);
    }
};
const upload = multer({storage: storage, limits: { fileSize: '4MB' }, fileFilter: fileFilter}).single("StudentImage")

const router = express.Router();
router.post('/image', upload, async (req, res)=>{    
    console.log(req.file);

})

console.log(req.file); 行打印出 undefined

【问题讨论】:

    标签: node.js reactjs express mongoose


    【解决方案1】:

    setState 是异步的,因此当您尝试将this.state.StudentImage 附加到data 时,不能保证您可以访问新的状态值:

        this.setState({
          StudentImage: e.target.files[0]
        });
        const data = new FormData() 
        data.append('StudentImage', this.state.StudentImage);
    

    this.setState 接受第二个参数,一个回调,让您可以访问新状态,所以这可能会更好:

        this.setState({
          StudentImage: e.target.files[0]
        }, () => {
          const data = new FormData() 
          data.append('StudentImage', this.state.StudentImage);
          axios.post('http://localhost:4000/students/image',data)
          console.log(this.state.StudentImage.lastModified)
        });
    

    或者直接使用StudentImage而不是this.state.StudentImage,这样会简单一些:

        const StudentImage = e.target.files[0];
        this.setState({ StudentImage });
        const data = new FormData();
        data.append('StudentImage', StudentImage);
        axios.post('http://localhost:4000/students/image',data)
        console.log(StudentImage.lastModified)
    

    另一件事:在节点中,我认为您想要req.body 而不是req.file。

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多