I want to upload an image to my blog with node.js

泪湿孤枕 提交于 2021-02-10 16:15:32

问题


I am creating a small blog with node.js, my blog works perfectly locally, but I would like to add images to my article, I already use bootstrap to display my input but at the node. i can not save my image can you help me please?

I use Mongoose as an online server (I work under linux)

server.js

var express = require('express'),
swig = require('swig'),
path = require('path'),
mongoose = require('mongoose'),
app = express();

app.use(express.logger());
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', swig.renderFile);

app.set('view engine', 'html');
app.set('views', __dirname+'/views');

mongoose.connect('mongodb://**:**@**.mlab.com:**/blog');
var Article = mongoose.model('Article', {title: String, content: 
String, updated: Date}); 

app.get('/', function(req, res){

    Article.find({}).sort({updated: -1}).exec(function(err, articles){
        if(err){throw err;}

        data = {title: 'Mon super blog', articles: articles};
        res.render('index', data);
    })
 });

app.get('/article/:id', function(req, res){
    var article = Article.findById(req.params.id, function(err, 
article){
        if(err){throw err}
            var data = {article: article, title: article.title};
        res.render('article', data);
    });
 });


 app.post('/update/:id', function(req, res){
    Article.update({ _id : req.params.id}, {
        title: req.body.titre, content: req.body.contenu, updated: new 
 Date()
    },
    function(err){
        if(err){throw err;}
        res.redirect('/');
    });
});

app.get('/edit/:id', function(req, res){
    var article = Article.findById(req.params.id, function(err, 
article){
        if(err){throw err}
        var data = {article: article, title: 'Modifier ' 
 +article.title};
        res.render('edit', data);
    })
})


app.get('/destroy/:id', function(req, res){
    Article.remove({ _id : req.params.id}, function(err){
        if(err){throw err;}
        res.redirect('/');
    });
});

app.get('/create', function(req, res){
    var data = {title: 'Ajouter un article'};
    res.render('create', data);
});

app.post('/store', function(req, res){
    var article = new Article({
        title: req.body.titre,
        content: req.body.contenu,
        updated: new Date()
    });

    article.save(function(err, article){
        if(err){throw err;}
        res.render('created');
    });
});

app.listen(3000);
console.log('App running http://localhost:3000');

create.html

{% extends 'layout.html' %}

{% block content %}

<form role="form" action="/store" method="post">

<div class="form-group">
<label for="titre">Titre</label>
<input type="text" name="titre" class="form-control" 
placeholder="titre de l'article" required>
</div>

<div class="form-group">
    <label for="titre">Titre</label>
    <label for="contenu">Contenu de l'article</label>
    <textarea name="contenu" class="form-control" placeholder="Contenu 
de l'article" rows="3" required></textarea>
</div>

<form>
    <div class="form-group">
        <label>Telecharger une image</label>
        <input type="file" class="form-control-file" name="img">
    </div>
</form>

<button type="submit" class="btn btn-default">Ajouter </button>

</form>


{% endblock %}

article.html

{% extends 'layout.html' %}

{% block content %}

<span class="pull-right"><a class="btn btn-danger remove" 
href="/destroy/{{article.id}}">Le bouton magique</a></span>

<h1>{{article.title}}</h1>


<p>{{article.content}}</p>

<span class="date">
Mis à jour {{article.updated.getDate()}} / 
{{article.updated.getMonth() +1}} / {{article.updated.getFullYear()}}
</span>

<div class="pull-right">
<a href="/edit/{{article.id}}" class="btn btn-default">Modifier</a>
</div>

{% endblock %}

回答1:


You can use multer library to upload and save file into local storage and save relative path to your database.

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

app.post('/create',upload.single('img'), function(req,res)
{
  var article = new Article({
    title: req.body.titre,
    content: req.body.contenu,
    updated: new Date(),
    // you can store path here
  });

  article.save(function(err, article){
    if(err){throw err;}
    res.render('created');
  });
});

You can read more at here

But what I would suggest is use any cloud storage like s3 or Azure storage and store file there from client side directly and pass that url to server to store in DB.

Client > Requst server for temporary cred > upload file using that cred > call /create on server including url.




回答2:


finally here is the solution I had found last week, I want to thank you

server.js

var express = require('express'),
multer = require('multer'),
swig = require('swig'),
path = require('path'),
mongoose = require('mongoose'),
app = express(); 

//app.use(express.logger());
app.use(express.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', swig.renderFile);

app.set('view engine', 'html');
app.set('views', __dirname+'/views');




mongoose.connect('mongodb://*:*@ds145438.mlab.com:45438/blog');
var Article = mongoose.model('Article', {title: String,img: String, 
content: String, updated: Date}); 

app.get('/', function(req, res){

    Article.find({}).sort({updated: -1}).exec(function(err, articles){
        if(err){throw err;}

        data = {title: 'Mon super blog', articles: articles};
        res.render('index', data);
    })
 });

 app.get('/article/:id', function(req, res){
    var article = Article.findById(req.params.id, function(err, 
 article){
        if(err){throw err}
            var data = {article: article, title: article.title};
        res.render('article', data);
    });
  });


 app.post('/update/:id', function(req, res){
    Article.update({ _id : req.params.id}, {
        title: req.body.titre,
        img: '/uploads/' + req.file.filename,
        content: req.body.contenu,
        updated: new Date(),
    },
    function(err){
        if(err){throw err;}
        res.redirect('/');
    });
  });

  var upload = multer({dest: __dirname + '/public/uploads'});

  app.post('/create',upload.single('img'), function(req,res)
  {

    console.log('req : ', req.file)
    var article = new Article({
    title: req.body.titre,
    img: '/uploads/' + req.file.filename,
    content: req.body.contenu,
    updated: new Date(),
   });

   article.save(function(err, article){
    if(err){throw err;}
    res.render('created');
   });
 });


 app.get('/edit/:id', function(req, res){
    var article = Article.findById(req.params.id, function(err, 
 article){
        if(err){throw err}
        var data = {article: article, title: 'Modifier ' + 
 article.title};
        res.render('edit', data);
    })
 })


 app.get('/destroy/:id', function(req, res){
    Article.remove({ _id : req.params.id}, function(err){
        if(err){throw err;}
        res.redirect('/');
    });
 });

  app.get('/create', function(req, res){
    var data = {title: 'Ajouter un article'};
    res.render('create', data);
  });

  app.post('/store', upload.single('img'), function(req, res){

    console.log('req.body : ', req.body)
    console.log('req.file : ', req.file)
    var article = new Article({
        title: req.body.titre,
        img: '/uploads/' + req.file.filename,
        content: req.body.contenu,
        updated: new Date(),
    });

    article.save(function(err, article){
        if(err){throw err;}
        res.render('created');
    });
   });

  app.listen(3000);
  console.log('App running http://localhost:3000');

article.html

{% extends 'layout.html' %}

{% block content %}

<span class="pull-right"><a class="btn btn-danger remove" href="/destroy/{{article.id}}">Le bouton magique</a></span>

<h1>{{article.title}}</h1>

    <img src="{{article.img}}" alt="img">


<p>{{article.content}}</p>

<span class="date">
Mis à jour {{article.updated.getDate()}} / {{article.updated.getMonth() +1}} / {{article.updated.getFullYear()}}
</span>

<div class="pull-right">
<a href="/edit/{{article.id}}" class="btn btn-default">Modifier</a>
</div>

{% endblock %}


来源:https://stackoverflow.com/questions/48986925/i-want-to-upload-an-image-to-my-blog-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!