在expressjs

时间:2019-01-28 03:04:22

标签: node.js express file-upload multer

使用表单上传图像的简单正确方法是什么?

我想用表格上传图像。我曾尝试解决,但遇到了“意外领域”。我已经安装了multer,并遵循了一个简单的教程,但是无法按预期工作

这是我的路线

var express = require('express');
const multer = require('multer'); 
var router = express.Router();

const multerConfig = {
  storage: multer.diskStorage({
    //setup where the user's file will go
    destination: function(req, file, next){
      next(null, './public/images');
    },
    //then give the file a unique name here
    filename: function(reg, file, next){
      console.log(file);
      const ext = file.mimetype.split('/')[1];
      next(null, file.fieldname + '-' + Date.now() + '.'+ext)
    }
  }),
  //a means of ensuring only images are uploaded.
  fileFilter: function(req, file, next){
    if(!file){
      next();
    }
    const image = file.mimetype.startsWith('image/');
    if(image){
      console.log('photo uploaded');
      next(null, true);
    }else{
      console.log('file not supported');

      return next();
    }
  }
}

var bookControllers = require("../controllers/bookControllers")
//const csrf = require("../app");

/* GET home page. 
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
*/

router.get('/', bookControllers.index);
router.post('/addbooks', multer(multerConfig).single('photo'), bookControllers.addbooks);
router.get('/addbooks/:id/:book_url', bookControllers.vieweachbook);
//router.get('/addbooks/:id/edit', bookControllers.edit);
router.get("/:id/edit", bookControllers.edit);
router.get('/:id/delete', bookControllers.delete);
router.put("/:id/update", bookControllers.update);

module.exports = router;

这是bookControllers.js中的addbooks

exports.addbooks = function (req, res)
{
    const schema = Joi.object().keys({
        book_name: Joi.string().trim().min(6).max(25).required(),
        summaries: Joi.string().trim().required(),
        isbn: Joi.number().required(),
        categories: Joi.string().trim().required(),

    });
    Joi.validate(req.body, schema, (err, result) => {
        if(err){
            console.log(err)
            return res.redirect("/");
        }

        var url = slug(req.body.categories, {lower: true});
        var book_url = slug(req.body.book_name, {lower: true});

        //I have to get the auth user and add to the field later
        var author = "1";

        //Perform knex insert into db
        knex('book').insert({
            book_name: req.body.book_name,
            author: author,
            summary: req.body.summaries,
            isbn: req.body.isbn,
            category: req.body.categories,
            image: req.body.image,
            url: url,
            book_url: book_url

        }).then(function(result){
            console.log(err)
            return res.redirect('/');
        });
    });
}

这是表格

    <div class="col-lg-4">
          <div class="card">
            <div class="card-header bg-primary"> Add Books </div>
             <form id="c_form-h" class="" method="post" action="/addbooks" enctype="multipart/form-data" style="padding: 5px;">  
            <div class="form-group row">
                 <label for="addbookname" class="col-6 col-form-label">Book Name</label>
             <div class="col-12">
                <input type="text" class="form-control" name="book_name" placeholder="Add Book Name" required> 
            </div>
            </div>


            <div class="form-group row">
                <label for="addsummary" class="col-6 col-form-label">Summary</label>
              <div class="col-12">  
              <textarea class="form-control" name="summaries" placeholder="Write Some Description" rows="3" required>   
              </textarea>
            </div>
        </div>


            <div class="form-group row">
                <label for="addcategory" class="col-9 col-form-label">Select Category</label>
              <div class="col-12">
                <input type="number" class="form-control" name="isbn" placeholder="ISBN" required> 
            </div>
            </div>

            <div class="form-group row">
                <label for="addimage" class="col-9 col-form-label">Add Image</label>
                <div class="col-12">
                  <input type="file" class="form-control-file" name="image" required> 
              </div>
              </div>


             <div class="form-group row">
                <label for="addcategory" class="col-9 col-form-label">Select Category</label>
               <div class="col-12">
                  <select class="form-control" name="categories" required>
                    <option></option>
                    <option>Fruits</option>
                    <option>Intercontinental Foods</option>
                    <option>3</option>
                    <option>4</option>
                  </select>
                </div>
                </div>
             <button type="submit" class="btn btn-primary">Submit</button>
          </form>
        </div>
        </div>

还可以给我一些有关图像更新的提示吗?我的意思是如何改变形象 谢谢

1 个答案:

答案 0 :(得分:0)

在您的HTML中,文件名为image

<input type="file" class="form-control-file" name="image" required> 

因此,您需要在multer上提及与image相同的文件名,而不是photo

//Replaced photo with image
router.post('/addbooks', multer(multerConfig).single('image'), bookControllers.addbooks);

参考:Multer - API Documentation

更新数据库上的路径:

您将在控制器上的req.file中获得文件信息,就像

{ fieldname, originalname, encoding, mimetype, destination, filename, path, size }

根据您的需要,您可以将文件信息保存在数据库中

knex('book').insert({
...
image: req.file.path,
....
}).then(function(result){