node.js - How to upload an image along with other text fields in angular 2.x or 4.x, serve in node js and save to mongoDB along with the image path -


am having weird problem, , ave seen fellow developers asking on same, have several modules hundle uploading files, , yes work fine, problem how add text fields along file upload. lets want angular 2 blog obliviously want add title, description, body or main content , add image accompany blog post. in case using uploader ng2-file uploader after image uploaded in specified folder /uploads next???? how save image path along text field blog post in mongodb when display article world see , everthing typed appears including image uploaded..a example twitter, choose image , add text , boom! retrieved image , text u typed..i have searched , see blogs text fields , no ways of including , serving images.any appreciated. thank you..

my angular 2 html code..

<h1>post database</h1>   <form class="well" (submit)="addpost($event)">      <!--text field input-->       <div class="form-group">         <input type="text" [(ngmodel)]="title" name="title" class="form-control" placeholder="add title...">          <input type="text" [(ngmodel)]="content" name="content" class="form-control" placeholder="add content...">          </div>     <!--input image uploading-->       <input type="file"        ngfileselect        [options]="options"        (onupload)="handleupload($event)"        (beforeupload)="beforeupload($event)">     <!--for form submiting-->       <input type = "submit" class = "btn btn-primary" value = "post">     </form> 

my angular 2 component.ts code..

import { component, oninit } '@angular/core'; import {dataservice} '../../services/data.service'; import {post} '../../shared/post';  @component({   selector: 'app-blog',   templateurl: './blog.component.html',   styleurls: ['./blog.component.css'] }) export class blogcomponent implements oninit {   //posts: post[];   private posts: post[]=[];   title: string;   content: string;     constructor(private dataservice:dataservice) {     console.log('constructor ran...');    }    ngoninit() {     console.log('ngoninit ran....');     this.dataservice.getposts()       .subscribe(data => this.posts = data);      this.dataservice.getposts().subscribe((posts) => {       //console.log(posts);       this.posts = posts;     })     }    //adding add data...this code works fine...     addpost(event){       event.preventdefault();         var newpost = {             title: this.title,             content: this.content,          }          this.dataservice.addpost(newpost)             .subscribe(post => {                 this.posts.push(post);                 this.title = '';                 this.content = '';             });     }      //updating data...      updatepost(post){         var _post = {             id:post._id,             title: post.title,             content: post.content,             isdone: !post.isdone         };          this.dataservice.updatepost(_post).subscribe(data => {             post.isdone = !post.isdone;         });     }      // hundling file upload......      uploadfile: any;   hasbasedropzoneover: boolean = false;   options: object = {     url: 'http://localhost:3000/upload'   };   sizelimit = 2000000;    handleupload(data): void {     if (data && data.response) {       data = json.parse(data.response);       this.uploadfile = data;       console.log(this.uploadfile);     }   }    fileoverbase(e:any):void {     this.hasbasedropzoneover = e;   }    beforeupload(uploadingfile): void {     if (uploadingfile.size > this.sizelimit) {       uploadingfile.setabort();       alert('file large');     }   }      deletepost(post){     if (confirm("are sure want delete " + post.title + "?")) {       var index = this.posts.indexof(post);       this.posts.splice(index, 1);        this.dataservice.deletepost(post._id)         .subscribe(null,           err => {             alert("could not delete user.");             // revert view original state             this.posts.splice(index, 0, post);           });     }   }  } 

my angular 2 data.service.ts code..

import { injectable } '@angular/core'; import {http, headers,requestoptionsargs} '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/topromise'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import { observable } 'rxjs/rx';  @injectable() export class dataservice {    baseurl = 'http://localhost:3000'; // our local hapi js api   private url: string = "http://localhost:3000/api/posts";    constructor(private http:http) {     console.log('data service connected...');    }    getposts(){     return this.http.get('http://localhost:3000/api/posts')     .map(res => res.json());   }    //get id from--users.service    getpost(id){     return this.http.get(this.getposturl(id))       .map(res => res.json());   }    addpost(newpost){         var headers = new headers();         headers.append('content-type', 'application/json');         return this.http.post('http://localhost:3000/api/posts', json.stringify(newpost), {headers: headers})             .map(res => res.json());     }     updatepost(post){     return this.http.put(this.getposturl(post.id), json.stringify(post))       .map(res => res.json());   }     deletepost(id){     return this.http.delete(this.getposturl(id))       .map(res => res.json());   }    private getposturl(id){     return this.url + "/" + id;   } } 

my node js app.js code...

const express = require ('express'); const path = require ('path'); const multer = require('multer'); const bodyparser = require ('body-parser'); const cors = require ('cors'); const passport = require ('passport'); const mongoose = require ('mongoose'); const config = require ('./config/database');  mongoose.connect(config.database, {     usemongoclient: true });  // know if connected database... mongoose.connection.on('connected', () => {     console.log('connected database ' + config.database); });  // checking errors when connecting database... mongoose.connection.on('error', (err) => {     console.log('database error: ' + err); });  const app = express();  const users = require ('./routes/users'); //const posts = require ('./routes/posts');  // port number... const port = 3000;//process.env.port || 8080;  // cors middleware... app.use(cors());  // set static folder... app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'uploads')));  // body parser middleware... app.use(bodyparser.json());  post =require('./models/post');  app.use(bodyparser.urlencoded({ extended: true })); // parsing application/x-www-form-urlencoded   // passport middleware... app.use(passport.initialize()); app.use(passport.session());  require ('./config/passport')(passport);  app.use('/users', users); //app.use('/api', posts);  // index route... app.get('/', (req, res) => {     res.send('invalid endpoint!'); });     app.get('/api/posts', (req, res) => {     post.getposts((err, posts) => {         if(err){             throw err;         }         res.json(posts);     }); });  app.get('/api/posts/:_id', (req, res) => {     post.getpostbyid(req.params._id, (err, post) => {         if(err){             throw err;         }         res.json(post);     }); });  app.post('/api/posts', (req, res) => {     var post = req.body;     post.addpost(post, (err, post) => {         if(err){             throw err;         }         res.json(post);     }); });  app.put('/api/posts/:_id', (req, res) => {     var id = req.params._id;     var post = req.body;     post.updatepost(id, post, {}, (err, post) => {         if(err){             throw err;         }         res.json(post);     }); });  app.delete('/api/posts/:_id', (req, res) => {     var id = req.params._id;     post.removepost(id, (err, post) => {         if(err){             throw err;         }         res.json(post);     }); });   //................................................................ var storage = multer.diskstorage({   destination: function (req, file, cb) {     cb(null, 'uploads/')   },    filename: function (req, file, cb) {     const ext = path.extname(file.originalname);     //cb(null, `${math.random().tostring(36).substring(7)}${ext}`);     cb(null, file.fieldname + '-' + date.now()+ext)   } })  var upload = multer({ storage: storage });  app.post('/upload', upload.any(), (req, res) => {   res.json(req.files.map(file => {         let ext = path.extname(file.originalname);         req.filename;      return {       //originalname: file.originalname,        filename: file.filename       }   }));  })   // start server... app.listen(port, ()  => {     console.log('server started on port ' +port); }); 

my post.js schema code..

const mongoose = require ('mongoose');  // post schema const postschema = mongoose.schema({      title:{         type: string,         required: true     },     content:{         type: string,         required: true     },     image_url:{         type: string     },     create_date:{         type: date,         default: date.now     } });  const post = module.exports = mongoose.model('post', postschema);  // posts module.exports.getposts = (callback, limit) => {     post.find(callback).limit(limit); }  // post module.exports.getpostbyid = (id, callback) => {     post.findbyid(id, callback); }  // add post module.exports.addpost = (post, callback) => {     post.create(post, callback); }  // update post module.exports.updatepost = (id, post, options, callback) => {     var query = {_id: id};     var update = {         title: post.title,         content: post.content,         image_url: post.image_url     }     post.findoneandupdate(query, update, options, callback); }  // delete post module.exports.removepost = (id, callback) => {     var query = {_id: id};     post.remove(query, callback); } 

the code above working me atleast simple angular 2 , or 4 blog. big question is, how path uploaded image in /uploads saved along title , content in mongodb collection when request article able display image uploaded exact blog post. hope shed light on how kind of uploading/posting , saving works. totally confused , research on subject lead dead end.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -