使用multer上传文件不适用于express.js应用程序

时间:2017-11-01 00:03:07

标签: node.js postgresql reactjs express multer

我有一个简单的博客应用程序,后端有Express.js,前端有React.js。我正在尝试添加一个功能来将图片添加到postgres数据库,我的架构看起来像这样。

    CREATE TABLE IF NOT EXISTS learningtable (
     id BIGSERIAL PRIMARY KEY,
     topstuff VARCHAR(255),
     bottomstuff VARCHAR(255),
     pic1 bytea
     );

我的上传表单如下所示。

    <form onSubmit={this.handleSubmit} >
      <input type="text" name="topstuff" placeholder="top" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
      <input type="text" name="bottomstuff" placeholder="bottomt" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
      <input type="file" name="pic1" /><br/>
      <input type="submit" value="yeah boy" />
    </form>

我的路由器文件看起来像这样

    const express = require('express');
    const myrouter = express.Router();
    const controller = require('../controllers/learningController');
    const multer = require('multer');

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
        cb(null, 'uploads')
       },
    filename: function (req, file, cb) {
     cb(null, file.fieldname + '-' + Date.now())
         }
       })

   var upload = multer({ storage: storage })

   myrouter.post('/', upload.single('pic1'), controller.create);

   module.exports = myrouter;

我的控制器是

     const controller = {};            

     controller.create = (req, res) => {
     console.log(req.body);
     console.log(req.file)
      LearningObject.create({
        topstuff: req.body.topstuff,
        bottomstuff: req.body.bottomstuff,
        pic1: req.file,
      })
       .then(jsonAfterAdding => {
         res.json({
          message: 'okay',
          jsonAfterAdding: jsonAfterAdding
       });
       }).catch(err => {
           console.log(err);
            res.status(400).json(err);
                });
             };

    module.exports = controller;

我的模型看起来像这样

    const db = require('../db/config');
    const LearningObject = {};

    LearningObject.create = (blahblah) => {
      return db.one (
        `INSERT INTO learningtable
         (topstuff, bottomstuff, pic1)
         VALUES ($1, $2, $3) RETURNING *
       `,
      [blahblah.topstuff, blahblah.bottomstuff, blahblah.pic1]
      );
     };


     module.exports = LearningObject;

当我在尝试上传后控制log req.file时,表示未定义。文本“topstuff”和“bottomstuff”会保存到数据库中,但我看不到文件夹或数据库中的图片。

1 个答案:

答案 0 :(得分:0)

尝试在html文件中更改此内容

<form onSubmit={this.handleSubmit} action='/' method="POST" enctype="multipart/form-data" >
      <input type="text" name="topstuff" placeholder="top" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
      <input type="text" name="bottomstuff" placeholder="bottomt" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
      <input type="file" name="pic1" /><br/>
      <input type="submit" value="yeah boy" />
    </form>