Multer正在本地上传我的图片,但不在我的数据库中

时间:2016-11-16 20:12:45

标签: node.js mongodb express mongoose multer

我想在我的博客文章中上传图片,但是有一个错误,图片在文件夹中是alredy但是当我看到数据库时,noimage.png设置为默认值... 我使用Multer,有我的代码:

Addpost.ejs

<% include ./partials/header %>
<form method="POST" action="/posts/add" enctype="multipart/form-data">
    <div class="form-group">
        <label>Title</label>
        <input class="form-control" name="title" type="text">
    </div>
    <div class="form-group">
        <label>Category</label>
        <select class="form-control" name="category">
            <% categories.forEach(function(category){ %>
                <option value="<%= category.title %>"><%= category.title %></option>
            <%  }) %>
        </select>
    </div>
    <div class="form-group">
        <label>Body</label>
        <textarea class="form-control" name="body"></textarea>
    </div>
    <div class="form-group">
        <label>Main Image</label>
        <input class="form-control" name="file" type="file">
    </div>
    <div class="form-group">
        <label>Author</label>
        <select class="form-control" name="author">
            <option value="Arsen Cenko">Arsen Cenko</option>
            <option value="John Doe">John Doe</option>
        </select>
    </div>
    <input class="btn btn-default" name
    ="submit" type="submit" value="save">
</form>
<script src="/app.js"></script>

PostSchema:

var mongoose = require("mongoose")
var postSchema = new mongoose.Schema({
title: String,
created: {type: Date, default: Date.now},
category: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Category"
    }
],
body: String,
file: String })
module.exports = mongoose.model("Post", postSchema);

Post.js Route

var express = require("express");
var router = express.Router();
var Post = require("../models/post");
var Category = require("../models/category");
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
   destination: function (req, file, cb) {
    cb(null, './public/images/uploads/')
   },
   filename: function (req, file, cb) {
     cb(null, Date.now() + path.extname(file.originalname)) 
  } });
 var upload = multer({ storage: storage });


 router.get("/add", function(req, res) {
     Category.find({}, function(err, categories){
         if(err){
            console.log(err);
         } else{
            res.render("addpost", {
                title: "Add Post",
                categories: categories
            })
         }
     })
})


router.post("/add", upload.single('image'), function(req, res){
var title       = req.body.title;
var category    = req.body.category;
var body        = req.body.body;
var author      = req.body.author;

if(req.files && req.files.image){
    var imageOriginalName = req.files.image.originalname;
    var imageName = req.files.image.fieldname;
    var imageMime = req.files.image.mimetype;
    var imagePath = req.files.image.path;
    var imageExt = req.files.image.extension;
    var imageSize = req.files.image.size;
} else {
    var imageName = "noimage.png";
}

var newPost = {title:title, category:category, body:body, author:author, image:imageName};

Post.create(newPost, function(err, newPost){
    if(err){
        console.log("Error");
    } else{
        res.redirect("/");
    }
})

})

谢谢:)

1 个答案:

答案 0 :(得分:0)

嘿,根据文件

https://github.com/expressjs/multer

使用upload.single('image')将您的文件放入&#34; req.file&#34;不在&#34; req.files&#34;

我认为这就是你的情况失败并跳到其他情况的原因。您无法像req.file.image.filename那样访问它,只需通过req.file.filename访问它即可。因为它已经是一个单一的&#34;文件。尝试控制台记录req.file以了解你得到了什么。

更新我认为错误在你的HTML中

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

应该是

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

html的name属性应与upload.single中的字符串相同。 所以在你的情况下

upload.single('image')

现在您将在req.file中收到文件。

希望它有所帮助。